Incrementing a date in JavaScript

后端 未结 17 2351
余生分开走
余生分开走 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 06:09

    This a simpler method , and it will return the date in simple yyyy-mm-dd format , Here it is

    function incDay(date, n) {
        var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
        fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
        return fudate;
    }
    
    

    example :

    var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
    var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
    var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
    

    Note

    incDay(new Date("2020-11-12"), 1); 
    incDay("2020-11-12", 1); 
    

    will return the same result .

提交回复
热议问题