嗨,我正在尝试使用字符串构造一个 javascript 日期对象,但它一直在构建错误的日期。它总是构建落后一天的一天。这是我的代码
var date = new Date('2006-05-17');
我想得到的日期是
Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)
但相反我得到
Tue May 16 2006 17:00:00 GMT-0700 (PDT)
嗨,我正在尝试使用字符串构造一个 javascript 日期对象,但它一直在构建错误的日期。它总是构建落后一天的一天。这是我的代码
var date = new Date('2006-05-17');
我想得到的日期是
Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)
但相反我得到
Tue May 16 2006 17:00:00 GMT-0700 (PDT)
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
实际发生的情况是解析器将破折号解释为格式为“YYYY-MM-DDTHH:mm:ss.sssZ”的 ISO-8601 字符串的开始,默认情况下为 UTC 时间(因此尾随 'Z ')。
您也可以使用“toISOString()”日期函数来生成此类日期。 http://www.w3schools.com/jsref/jsref_toisostring.asp
在 Chrome(不适用于 IE 10-)中,如果您在日期中添加“00:00”或“00:00:00”(没有“T”),那么无论破折号。;)
从“05”中删除前置零