我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
当前回答
我已经通过使用Moment Js库完成了 参考文献:https://momentjs.com/
startDate = new Date()
endDate = moment(startDate).add(2, "Months").format("YYYY-MM-DD")
endDate= new Date (endDate)
其他回答
简单的解决方案:2678400000是31天,单位为毫秒
var oneMonthFromNow = new Date((+new Date) + 2678400000);
更新:
使用这些数据来构建我们自己的函数:
2678400000 - 31天 2592000000 - 30天 2505600000 - 29天 2419200000 - 28天
有时有用的创建日期由一个操作符,如在BIRT参数
我在1个月前用:
new Date(new Date().setMonth(new Date().getMonth()-1));
我使用moment.js库进行日期-时间操作。 添加一个月的示例代码:
var startDate = new Date(...);
var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
endDateMoment.add(1, 'months');
这适用于所有的边缘情况。newMonth的奇怪计算处理负月份输入。如果新的月份与预期的月份不匹配(比如31 Feb),它会将月份的日期设置为0,这意味着“上个月的结束”:
function dateAddCalendarMonths(date, months) {
monthSum = date.getMonth() + months;
newMonth = (12 + (monthSum % 12)) % 12;
newYear = date.getFullYear() + Math.floor(monthSum / 12);
newDate = new Date(newYear, newMonth, date.getDate());
return (newDate.getMonth() != newMonth)
? new Date(newDate.setDate(0))
: newDate;
}
下面的函数在JavaScript中为日期添加月份(源代码)。它考虑了年的滚动和不同的月份长度:
function addMonths(date, months) { var d = date.getDate(); date.setMonth(date.getMonth() + +months); if (date.getDate() != d) { date.setDate(0); } return date; } // Add 12 months to 29 Feb 2016 -> 28 Feb 2017 console.log(addMonths(new Date(2016,1,29),12).toString()); // Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016 console.log(addMonths(new Date(2017,0,1),-1).toString()); // Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016 console.log(addMonths(new Date(2017,0,31),-2).toString()); // Add 2 months to 31 Dec 2016 -> 28 Feb 2017 console.log(addMonths(new Date(2016,11,31),2).toString());
上面的解决方案涵盖了从一个月移动的天数多于目标月份的边缘情况。如。
增加12个月至2020年2月29日(应该是2021年2月28日) 增加一个月至2020年8月31日(应该是2020年9月30日)
如果在应用setMonth时,月份的日期发生了变化,那么由于月份长度的差异,我们知道已经溢出到下一个月。在本例中,我们使用setDate(0)返回到上个月的最后一天。
注意:这个答案的这个版本取代了之前的版本(下面),之前的版本没有优雅地处理不同的月份长度。
var x = 12; //or whatever offset
var CurrentDate = new Date();
console.log("Current date:", CurrentDate);
CurrentDate.setMonth(CurrentDate.getMonth() + x);
console.log("Date after " + x + " months:", CurrentDate);