我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。

我宁愿不处理一年的滚动,也不愿意自己写函数。

有什么内置的东西可以做到这一点吗?


当前回答

最简单的解决方法是:

const todayDate = Date.now();
return new Date(todayDate + 1000 * 60 * 60 * 24 * 30* X); 

其中X是我们想要增加的月份数。

其他回答

只是在已接受的答案和评论上加上一点。

var x = 12; //or whatever offset
var CurrentDate = new Date();

//For the very rare cases like the end of a month
//eg. May 30th - 3 months will give you March instead of February
var date = CurrentDate.getDate();
CurrentDate.setDate(1);
CurrentDate.setMonth(CurrentDate.getMonth()+X);
CurrentDate.setDate(date);
d = new Date();

alert(d.getMonth()+1);

月份有一个基于0的指数,它应该警报(4),这是5(五月);

简单的解决方案:2678400000是31天,单位为毫秒

var oneMonthFromNow = new Date((+new Date) + 2678400000);

更新:

使用这些数据来构建我们自己的函数:

2678400000 - 31天 2592000000 - 30天 2505600000 - 29天 2419200000 - 28天

考虑到这些答案中没有一个会在月份变化时解释当年的情况,你可以在下面找到我做的一个答案,它应该可以处理这个问题:

方法:

Date.prototype.addMonths = function (m) {
    var d = new Date(this);
    var years = Math.floor(m / 12);
    var months = m - (years * 12);
    if (years) d.setFullYear(d.getFullYear() + years);
    if (months) d.setMonth(d.getMonth() + months);
    return d;
}

用法:

return new Date().addMonths(2);
var a=new Date();
a.setDate(a.getDate()+5);

如上所述的方法,您可以添加月到日期功能。