Javascript date, is this my error or did I find a bug?

后端 未结 3 1517
旧时难觅i
旧时难觅i 2021-01-18 03:55

I have a section of simple Javascript in my application that has a link \"Add Day\", which adds 1 day to a date. It always works perfectly, except when the date gets to be

3条回答
  •  礼貌的吻别
    2021-01-18 04:02

    Others spotted what the problem is.

    To fix it you can use the overloaded Date constructor that takes the year, month, and day:

    var aDate = new Date(2010, 10, 07);
    var aDatePlusOneDay = new Date(aDate.getFullYear(),
                                   aDate.getMonth(),
                                   aDate.getDate() + 1, // HERE
                                   aDate.getHours(),
                                   aDate.getMinutes(),
                                   aDate.getSeconds(),
                                   aDate.getMilliseconds()); 
    

    Here's a more generic solution that can increment any date by a given millisecond amount, taking changes to daylight savings into account:

    Date.addTicks = function(date, ticks) {
      var newDate = new Date(date.getTime() + ticks);
      var tzOffsetDelta = newDate.getTimezoneOffset() - date.getTimezoneOffset();
      return new Date(newDate.getTime() + tzOffsetDelta * 60000);
    }
    

    Adding a day to a Date object then is a matter of adding the number of milliseconds in one day:

    Date.addTicks(new Date(2010, 10, 7), 86400000); // new Date(2010, 10, 8)
    

    References:

    • Date.prototype.getTimezoneOffset

提交回复
热议问题