Javascript dates are a day off?

This question already has an answer here:

  • Why does Date.parse give incorrect results? 10 answers
  • Changing the format of a date string 2 answers

  • From here

    Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.

    Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.

    The following code should work for creating a Date in the local timezone with the correct date.

    utcDate = new Date("2017-07-30"); //Date object a day behind
    new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date
    

    Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.

    This might not work in areas ahead of UTC; it might advance an extra day. Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.

    链接地址: http://www.djcxy.com/p/18624.html

    上一篇: 如何修复FF和IE中的无效日期错误

    下一篇: JavaScript的日期是休息一天?