Do not pass strings to the Date constructor, it is notoriously bad at parsing strings.
(不要将字符串传递给Date构造函数,这在解析字符串时非常糟糕。)
IE 8, for one, will not parse ISO 8601 format strings at all and return NaN .(IE 8完全不会解析ISO 8601格式的字符串,并返回NaN 。)
It's really simple to write your own parser:(编写自己的解析器非常简单:)
function parseISOString(s) {
var b = s.split(/D+/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
Note also that if the time is 19:38:34.203 UTC and your timezone is UTC +0530, then the time in that timezone is 01:08:34 am on the following day, hence the difference in dates.
(还要注意,如果时间是UTC时间19:38:34.203,并且您的时区是UTC +0530,那么该时区中的时间是第二天的01:08:34,因此日期有所不同。)
For example, for a person on the east coast of Australia but not observing daylight saving (ie UTC +10), it's equivalent to:(例如,对于一个在澳大利亚东海岸但未遵守夏令时(即UTC +10)的人,它等同于:)
4 November, 2014 05:38:34
Edit(编辑)
So if you want to return it to an ISO date, you can use the getISO* methods to create whatever format that suits, eg
(因此,如果要将其恢复为ISO日期,则可以使用getISO *方法创建适合的任何格式,例如)
function isoFormatDMY(d) {
function pad(n) {return (n<10? '0' : '') + n}
return pad(d.getUTCDate()) + '/' + pad(d.getUTCMonth() + 1) + '/' + d.getUTCFullYear();
}
var s = '2014-11-03T19:38:34.203Z';
var date = parseISOString(s);
console.log(isoFormatDMY(date)) // 03/11/2014
or use ES5's toISOString :
(或使用ES5的toISOString :)
parseISOString('2014-11-03T19:38:34.203Z').toISOString(); // 2014-11-03T19:38:34.203Z
A simple polyfill for pre ES5 browsers:
(适用于ES5之前版本浏览器的简单polyfill:)
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function() {
var d = this;
// Padding functions
function pad(n) {return (n<10? '0' : '') + n}
function padd(n){return (n<100? '0' : '') + pad(n)}
return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +
'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' +
pad(d.getUTCSeconds()) + '.' + padd(d.getMilliseconds()) + 'Z';
}
}