简体   繁体   中英

Date.js parsing an ISO 8601 UTC date incorrectly

Using the javascript library Date.js I am finding that when i pass into the Date.parse() function an ISO 8601 formatted UTC 0 date I am getting an object that is representative of the same date but with the local time zone added.

For example,

Given the date: 2012-08-27T14:57:00Z (in ISO 8601 format), which is showing a time of 14:57 UTC, why would this be parsed as 14:57 GMT-400 as opposed to 10:57 GMT-400?

I have created a fiddle to show it in action.

Please let me know if there is in fact an error or if my understanding of the parsing result is incorrect.

Yep, it's a bug - even a reported one .

Might I recommend using Moment.js library instead? For example, this :

console.log(moment('2012-08-27T14:57:00Z').toString());

... will correctly recognize that UTC time is given.

This seems like an error with Date.js. Using new Date('2012-08-27T14:57:00Z') returns the correct date.

It's caused by a buggy implementation of DateJS's rather otherwise awesome grammar parser.

Basically the old version just checked to see if it could use the built in parser, the new version tries to use grammar parsing but forgets to try that original step first and the grammar parser fails to use the timezone (which is a bug, but a different one).

Replace the parse function with this one:

$D.parse = function (s) {
    var date, time, r = null;
    if (!s) {
        return null;
    }
    if (s instanceof Date) {
        return s;
    }

    date = new Date(Date._parse(s));
    time = date.getTime();
    // The following will be FALSE if time is NaN which happens if date is an Invalid Date 
    // (yes, invalid dates are still date objects. Go figure.)
    if (time === time) {
        return date;
    } else {
        // try our grammar parser
        try {
            r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
        } catch (e) {
            return null;
        }
        return ((r[1].length === 0) ? r[0] : null);
    }
};

Updated version of the core code (and will be fixing open bugs in the future) available here:

https://github.com/abritinthebay/datejs/

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