如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?


当前回答

    //the_day is 2013-12-31
    var the_day = Date.UTC(2013, 11, 31); 
    // Now, the_day will be "1388448000000" in UTC+8; 
    var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
    // Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"

其他回答

int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);

代码笔

var天数=2;var newDate=新日期(Date.now()+天*24*60*60*1000);document.write(“今日:<em>”);document.write(new Date());document.write('</em><br/>新建:<strong>');document.write(newDate);

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

使用setDate()添加日期并不能解决您的问题,请尝试在2月份添加一些天,如果您尝试在其中添加新的天,则不会产生您预期的结果。

date d = new Date() // current date

date tomorrow = d.setMonth(d.getMonth(),d.getDate()+1) // return a date incremented by 0 months and 1 day
new Date(Date.now() + 2000 * 86400)

此代码段使用“2000”参数为当前日期添加两天。您可以通过更新第二个参数中的“2000”值来调整天数。

您可以使用这种单行格式,使用本机JavaScript日期将日期添加到当前日期。

我实现的最简单的方法是使用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)

`