简体   繁体   中英

Convert ISO8601 date to epoch format (unix timestamp)

如何使用javascript将ISO 8601日期(例如20140107)转换为Unix时间戳(例如1389120125)?

If you're using a browser with ECMAscript 5 support, Date.parse() accepts an ISO-8601 datestring and returns an epoch value in milliseconds, so just divide that by 1000 and you're done.

However

Contrary to what you state, your input string doesn't conform to the ISO-8601 subset defined in ECMAscript because it's lacking the dashes between the individual fields. As far as I know, the dashes are mandatory for EMCAscript (even though ISO 8601 itself allows the dashless, or basic, format). So maybe you'll have to do some string parsing and use one of Date's constructors and its getTime() method to obtain the same

new Date(year, month [, day, hour, minute, second, millisecond]);

If you want to remain compatible with older browsers but still use Date.parse, you could consider including this shim

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