Javascript Date string constructing wrong date

This question already has an answer here:

  • Why does Date.parse give incorrect results? 10 answers

  • When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.

    If you want local dates, then try using slashes instead, like this:

    var date = new Date('2006/05/17');
    

    Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.

    var date = new Date(2006,4,17);
    

    However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.

    var m = moment('2006-05-17','YYYY-MM-DD');
    m.format(); // or any of the other output functions
    

    从“05”删除前置零


    What actually happens is that the parser is interpreting your dashes as the START of an ISO-8601 string in the format "YYYY-MM-DDTHH:mm:ss.sssZ", which is in UTC time by default (hence the trailing 'Z').

    You can produce such dates by using the "toISOString()" date function as well. http://www.w3schools.com/jsref/jsref_toisostring.asp

    In Chrome (doesn't work in IE 10-) if you add " 00:00" or " 00:00:00" to your date (no 'T'), then it wouldn't be UTC anymore, regardless of the dashes. ;)

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

    上一篇: DD HH:MM:SS T

    下一篇: Javascript日期字符串构造错误的日期