Search code examples
javascriptdatetimedatejs

Parse specific date time format in Javascript


I have a date in the following format:

2012-12-09T02:08:34.6225152Z

I'm using the datejs javascript library and would like the parse the above date, but I can't seem to figure out the proper format string. I've tried the following, but it doesn't work.

Date.parse('2012-12-09T02:08:34.6225152Z', 'yyyy-MM-ddTHH:mm:ss.fffffffZ');

If it's easier, I'm also open to parsing the string in native javascript.


Solution

  • I ended up solving this problem by changing the format of the string as it was sent to Javascript. Instead of 2012-12-09T02:08:34.6225152Z I changed the JSON serializer to output 1363607010099 by using the following code:

    var serializer = new JsonNetSerializer(new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
        NullValueHandling = NullValueHandling.Ignore
    });
    

    I then changed my javascript to parse the date using this function that I found:

    String.prototype.toDate = function () {
        "use strict";
        var match = /\/Date\((\d{13})\)\//.exec(this);
        return match === null ? null : new Date(parseInt(match[1], 10));
    };
    

    Finally, I output the date using this bit of code (taking advantage of the DateJS library):

    myTime.toDate().toString('h:mm:ss tt dd-MMM-yyyy')
    

    And it works. This seems a bit hackish, so I'm more than open to consider alternatives.