我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
当前回答
所有这些看起来都太复杂了,我猜这引发了一场关于增加“一个月”到底是什么意思的争论。是指30天吗?是从1号到1号的意思吗?从最后一天到最后一天?
如果是后者,那么加一个月到2月27日就会到3月27日,但加一个月到2月28日就会到3月31日(闰年除外,会到3月28日)。那么从3月30日减去一个月…2月27日吗?谁知道……
对于那些寻找简单解决方案的人来说,只需要增加几毫秒就可以了。
function getDatePlusDays(dt, days) {
return new Date(dt.getTime() + (days * 86400000));
}
or
Date.prototype.addDays = function(days) {
this = new Date(this.getTime() + (days * 86400000));
};
其他回答
有时有用的创建日期由一个操作符,如在BIRT参数
我在1个月前用:
new Date(new Date().setMonth(new Date().getMonth()-1));
var a=new Date();
a.setDate(a.getDate()+5);
如上所述的方法,您可以添加月到日期功能。
这适用于所有的边缘情况。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;
}
最简单的解决方法是:
const todayDate = Date.now();
return new Date(todayDate + 1000 * 60 * 60 * 24 * 30* X);
其中X是我们想要增加的月份数。
从所给出的许多复杂而丑陋的答案可以看出,日期和时间对于使用任何语言的程序员来说都是一场噩梦。我的方法是将日期和“delta t”值转换为Epoch Time(以毫秒为单位),执行任何算术运算,然后转换回“人类时间”。
// Given a number of days, return a Date object
// that many days in the future.
function getFutureDate( days ) {
// Convert 'days' to milliseconds
var millies = 1000 * 60 * 60 * 24 * days;
// Get the current date/time
var todaysDate = new Date();
// Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
var futureMillies = todaysDate.getTime() + millies;
// Use the Epoch time of the targeted future date to create
// a new Date object, and then return it.
return new Date( futureMillies );
}
// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );
这是为一个略有不同的用例编写的,但您应该能够轻松地将其用于相关任务。
编辑:完整的源代码在这里!