如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
这些答案让我感到困惑,我更喜欢:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。
使用毫秒构造函数可以得到所需的日期对象。
其他回答
就这么简单:
new Date((new Date()).getTime() + (60*60*24*1000));
我试图解决类似的问题,我更喜欢getTime方法,但有一些奇怪的基于时区的副作用。
ofc将“今天”替换为您需要的任何日期,并将时间也输入。关键是获取UTC时间,然后用毫秒来做加法,以避免这些副作用。
var now = new Date(Date.now());
var today = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
const dayInMs = 86400000; //24 hours
const tomorrow = new Date(today.getTime() + dayInMs);
我实现的最简单的方法是使用Date()本身。`
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
我昨晚创建了这些扩展:可以传递正值或负值;
例子:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
这些答案让我感到困惑,我更喜欢:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。
使用毫秒构造函数可以得到所需的日期对象。