我希望使用javascript获得六个月之前的日期。
我使用以下方法。
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);
这是正确的方式还是更好的方式来获得过去六个月的日期。
如果这个问题得到解决,我想应用这个逻辑来获取过去2个月和过去10年等过去的日期等。
如果任何身体在jquery中给出解决方案对我也很有帮助。 提前谢谢。
答案 0 :(得分:6)
向日期添加更多功能
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;
};
<强>用法强>
var date = new Date();
/* get month back */
date.addDays(-30);
/* get half a year back */
date.addDays(-30 * 6);
如果您只需要日期,则无需额外的库。您还可以根据需要为Date的原型创建更多功能。
答案 1 :(得分:1)
答案 2 :(得分:1)
尝试:
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());