Calculate Date with start date and number of days with javascript

前端 未结 4 1661
予麋鹿
予麋鹿 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("-");
    }
    
    0 讨论(0)
  • 2021-01-27 13:21

    Use javascript date format:

    How to format a JavaScript date

    So you don't have to manually try to parse date strings.

    0 讨论(0)
  • 2021-01-27 13:23

    On October 28th the time changes from DST to "normal", so the day is not equal 24h. That may cause issues in your code.

    Also why (days-1) * 24 * 60 * 60 * 1000? If you set days to 1 the whole expression evaluates to zero...

    0 讨论(0)
  • 2021-01-27 13:27

    There's an easier way to achieve that : http://jsfiddle.net/pjambet/wZEFe/2/

    0 讨论(0)
提交回复
热议问题