将 X 个月添加到日期的 JavaScript 函数 [英] JavaScript function to add X months to a date
问题描述
我正在寻找将 X 个月添加到 JavaScript 日期的最简单、最简洁的方法.
I’m looking for the easiest, cleanest way to add X months to a JavaScript date.
是否有内置的东西可以做到这一点?
Is there something built in that can do this?
推荐答案
以下函数在 JavaScript 中为日期添加月份 (source).它考虑了年份滚动和不同的月份长度:
The following function adds months to a date in JavaScript (source). It takes into account year roll-overs and varying month lengths:
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());
上述解决方案涵盖了从天数多于目标月份的月份移动的边缘情况.例如.
The above solution covers the edge case of moving from a month with a greater number of days than the destination month. eg.
- 向 2020 年 2 月 29 日添加十二个月(应该是 2021 年 2 月 28 日)
- 将 2020 年 8 月 31 日(应该是 2020 年 9 月 30 日)增加一个月
如果在应用 setMonth
时当月中的某天发生变化,那么我们知道由于月长不同,我们已经溢出到下个月.在这种情况下,我们使用 setDate(0)
移回上个月的最后一天.
If the day of the month changes when applying setMonth
, then we know we have overflowed into the following month due to a difference in month length. In this case, we use setDate(0)
to move back to the last day of the previous month.
注意:这个答案的这个版本取代了早期版本(下面),它不能很好地处理不同的月份长度.
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);
这篇关于将 X 个月添加到日期的 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!