我正在寻找最简单,最干净的方法来增加X个月的JavaScript日期。
我宁愿不使用handle the rolling over of the year,也不想使用write my own function。
有没有内置的东西可以做到这一点?
发布于 2015-05-05 02:09:28
我正在为date-time manipulations使用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');
发布于 2016-04-03 06:28:27
考虑到当月份发生变化时,这些答案都不会考虑到当前年份,你可以在下面找到一个我做的答案,它应该可以解决这个问题:
方法:
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);
发布于 2016-03-31 19:00:57
取自@bmpsini和@Jazaret响应,但不扩展原型:使用普通函数(Why is extending native objects a bad practice?):
function isLeapYear(year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
}
function getDaysInMonth(year, month) {
return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
function addMonths(date, value) {
var d = new Date(date),
n = date.getDate();
d.setDate(1);
d.setMonth(d.getMonth() + value);
d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));
return d;
}
使用它:
var nextMonth = addMonths(new Date(), 1);
https://stackoverflow.com/questions/2706125
复制相似问题