In Javascript “d.setDate(d.getDate() + 1)” gives wrong answer in days when was time change

后端 未结 1 1578
梦如初夏
梦如初夏 2021-01-22 07:23

I have following code:

var d = new Date(\'2016-03-27\');
console.log(d.getDate(), d);
d.setDate(d.getDate() + 1);
console.log(d.getDate(), d);

相关标签:
1条回答
  • 2021-01-22 08:00

    Since you are working with UTC format dates, and you want to ignore local timezone changes such as daylight savings time, you should always use getUTCDate() and setUTCDate(). UTC has no daylight savings.

    var d = new Date('2016-03-27');
    console.log(d.getUTCDate(), d);
    d.setUTCDate(d.getUTCDate() + 1);
    console.log(d.getUTCDate(), d);
    

    Also consider JavaScript date libraries such as moment.js if you have more complex requirements.

    0 讨论(0)
提交回复
热议问题