javascript date + 1

后端 未结 7 1374
逝去的感伤
逝去的感伤 2020-12-29 02:34

How do I take today\'s date and add 1 day to it?

If possible, inline please?

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 02:51

    If by "add 1 day to it" you mean "add 24 hours", that is, add 24*60*60*1000 milliseconds to a JavaScript date object, then the correct solution is:

    var d = new Date();
    d.setTime(d.getTime() + 86400000);
    console.log('24 hours later');
    console.log(d);
    

    As @venkatagiri pointed out in an earlier comment, this will in fact add 24 hours to the current JavaScript date object in all scenarios, while d.setDate(d.getDate() + 1) will NOT if a Daylight Savings Time cross-over is involved. See this JSFiddle to see the difference in context of the 2013 start of DST (at March 10, 2013 at 2:00 AM, DST locale time moved forward an hour). setDate() in this scenario only adds 23 hours, while setTime() adds 24.

提交回复
热议问题