Incrementing a date in JavaScript

后端 未结 17 2341
余生分开走
余生分开走 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:45

    You first need to parse your string before following the other people's suggestion:

    var dateString = "2010-09-11";
    var myDate = new Date(dateString);
    
    //add a day to the date
    myDate.setDate(myDate.getDate() + 1);
    

    If you want it back in the same format again you will have to do that "manually":

    var y = myDate.getFullYear(),
        m = myDate.getMonth() + 1, // january is month 0 in javascript
        d = myDate.getDate();
    var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
    dateString = [y, pad(m), pad(d)].join("-");
    

    But I suggest getting Date.js as mentioned in other replies, that will help you alot.

提交回复
热议问题