The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
(字符串解析的最佳字符串格式是日期ISO格式以及JavaScript Date对象构造函数。)
Examples of ISO format: YYYY-MM-DD
or YYYY-MM-DDTHH:MM:SS
.
(ISO格式的示例: YYYY-MM-DD
或YYYY-MM-DDTHH:MM:SS
。)
But wait!
(可是等等!)
Just using the "ISO format" doesn't work reliably by itself. (仅仅使用“ ISO格式”本身不能可靠地工作。)
String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). (字符串有时会解析为UTC,有时会解析为本地时间(基于浏览器供应商和版本)。)
The best practice should always be to store dates as UTC and make computations as UTC. (最佳做法应始终是将日期存储为UTC并进行计算为UTC。)
To parse a date as UTC, append a Z - eg: new Date('2011-04-11T10:20:30Z')
.
(要将日期解析为UTC,请附加Z ,例如: new Date('2011-04-11T10:20:30Z')
。)
To display a date in UTC, use .toUTCString()
,
(要以UTC显示日期,请使用.toUTCString()
,)
to display a date in user's local time, use .toString()
.
(要显示用户当地时间的日期,请使用.toString()
。)
More info on MDN |
(有关MDN的更多信息|)
Date and this answer . (日期和这个答案 。)
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, eg: new Date('2011', '04' - 1, '11', '11', '51', '00')
.
(为了与旧版本的Internet Explorer兼容(小于9的IE版本在Date构造函数中不支持ISO格式),应将datetime字符串表示形式拆分为其各个部分,然后可以使用带datetime组成部分的构造函数,例如: new Date('2011', '04' - 1, '11', '11', '51', '00')
。)
Note that the number of the month must be 1 less. (请注意,月份数必须少1。)
Alternate method - use an appropriate library:
(替代方法-使用适当的库:)
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
(您还可以利用Moment.js库,该库允许解析具有指定时区的日期。)