我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
当前回答
来自@bmpsini和@Jazaret的回复,但没有扩展原型:使用普通函数(为什么扩展本机对象是一种糟糕的做法?)
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);
其他回答
简单的解决方案: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);
有时有用的创建日期由一个操作符,如在BIRT参数
我在1个月前用:
new Date(new Date().setMonth(new Date().getMonth()-1));
一个简单的答案可以是:
function addMonthsToDate(date, numMonths){
// Add months
date.setMonth(date.getMonth() + numMonths);
// Zero the time component
date.setHours(0, 0, 0, 0);
return date;
}
这可以被称为-增加两个月:
console.log(addMonthsToDate(new Date(),2));
我已经通过使用Moment Js库完成了 参考文献:https://momentjs.com/
startDate = new Date()
endDate = moment(startDate).add(2, "Months").format("YYYY-MM-DD")
endDate= new Date (endDate)