Calculate Date with start date and number of days with javascript

前端 未结 4 1662
予麋鹿
予麋鹿 2021-01-27 12:51

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange res

4条回答
  •  无人及你
    2021-01-27 13:10

    Likely your local timezone changes because of the end of the daylight saving time.

    > new Date(2012, 9, 28)
    Sun Oct 28 2012 00:00:00 GMT+0200
    > // 48 hours later:
    > new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
    Mon Oct 29 2012 23:00:00 GMT+0100
    

    Always use the UTC methods!

    BTW, adding days is much more easier with setDate, which also works around timezone issues:

    function calculateDateFromDays(startDate, days) {
        var datestrings = startDate.split("-"),
            date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
        date.setDate(date.getDate() + days);
        return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
    }
    

提交回复
热议问题