Incrementing a date in JavaScript

后端 未结 17 2166
余生分开走
余生分开走 2020-11-22 05:15

I need to increment a date value by one day in JavaScript.

For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript v

17条回答
  •  再見小時候
    2020-11-22 05:47

    Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):

    Date.prototype.shiftDays = function(days){    
      days = parseInt(days, 10);
      this.setDate(this.getDate() + days);
      return this;
    }
    
    $date = new Date(2014, 9, 16,0,1,1);
    $date.shiftDays(1);
    console.log($date+"");
    $date.shiftDays(1);
    console.log($date+"");
    $date.shiftDays(1);
    console.log($date+"");
    $date.shiftDays(1);
    console.log($date+"");
    

    Result:

    Fri Oct 17 2014 00:01:01 GMT-0300
    Sat Oct 18 2014 00:01:01 GMT-0300
    Sat Oct 18 2014 23:01:01 GMT-0300
    Sun Oct 19 2014 23:01:01 GMT-0200
    

    Adding one Hour to the date, will make it work perfectly (but does not solve the problem).

    $date = new Date(2014, 9, 16,0,1,1);
    

    Result:

    Fri Oct 17 2014 01:01:01 GMT-0300
    Sat Oct 18 2014 01:01:01 GMT-0300
    Sun Oct 19 2014 01:01:01 GMT-0200
    Mon Oct 20 2014 01:01:01 GMT-0200
    

提交回复
热议问题