简体   繁体   中英

Convert DateTime string to timestap in javascript

if dd = "2012-08-20 01:16:00"; converting this date to time-stamp (as in the following code)

var t = new Date(dd).getTime();

http://jsfiddle.net/userdude/DHxwR/

the result t = NaN why ?

According to ECMA-262 (§15.9.1.15, Date Time String Format , page 169), the only date string format required to be accepted is:

[+YY]YYYY[-MM[-DD]][THH:mm[:ss[.sss]]]Z

where Z is either Z (for UTC) or an offset consisting of either a + or a - followed by HH:mm . Any other formats that happen to be supported by a particular browser should not be relied upon, as continued support is not guaranteed.

Therefore, replace the space with a T and append either a Z , or a fixed time zone offset before passing it to the Date constructor. For example, if the date and time are in the UTC+8 zone:

var dd = "2012-08-20 01:16:00";
var t = new Date(dd.replace(' ', 'T') + '+08:00').getTime();

This will return the number of milliseconds from January 1, 1970, midnight UTC, to the date you have specified, treated as either universal time (if you appended Z ) or a time local to the fixed time zone offset that you specify.

Please note that this will act differently in that the date is not simply treated as time local to the user's system time zone as your question's example does. However, I can't think of a situation where doing that would be useful, because you'd get different results depending on the user's configuration — but in reality, the time difference between two dates is always the same no matter where you are.

尝试在年,月和日值之间使用空格或逗号。

这很简单:

+(new Date("2012-08-20 01:16:00"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM