使用 Javascript 获取上一个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9192956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Previous Date Using Javascript
提问by user1049997
I want to get the before six months date using javascript.
我想使用 javascript 获取前六个月的日期。
I am using the following method.
我正在使用以下方法。
var curr = date.getTime(); // i will get current date in milli seconds
var prev_six_months_date = curr - (6* 30 * 24 * 60* 60*1000);
var d = new Date();
d.setTime(prev_six_months_date);
Is this the right way or any better way to get the last six months date.
这是获得过去六个月日期的正确方法还是任何更好的方法。
If this get fixed I want to apply this logic to get previous dates like last 2 months and last 10 years etc.
如果此问题得到解决,我想应用此逻辑来获取过去的日期,例如过去 2 个月和过去 10 年等。
If any body give the solution in jquery also very helpful to me. Thanks in advance.
如果任何机构在 jquery 中给出解决方案也对我很有帮助。提前致谢。
回答by Tx3
Add more functionality to the Date
为日期添加更多功能
Date.prototype.addDays = function (n) {
var time = this.getTime();
var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
this.setTime(changedDate.getTime());
return this;
};
Usage
用法
var date = new Date();
/* get month back */
date.addDays(-30);
/* get half a year back */
date.addDays(-30 * 6);
No need for extra libraries, if this is only thing you need regarding dates. You can also create more functions to the Date's prototype according to your needs.
不需要额外的库,如果这只是你需要的关于日期的东西。您还可以根据需要为 Date 的原型创建更多功能。
回答by J. Holmes
回答by pete
Try:
尝试:
var curr = new Date();
var prev_six_months_date = new Date(curr);
var prev_two_months_date = new Date(curr);
var prev_ten_years_date = new Date(curr);
prev_six_months_date.setMonth(curr.getMonth() - 6);
prev_two_months_date.setMonth(curr.getMonth() - 2);
prev_ten_years_date.setFullYear(curr.getFullYear() - 10);
console.log(prev_six_months_date.toString());
console.log(prev_two_months_date.toString());
console.log(prev_ten_years_date.toString());
console.log(curr.toString());