Matt Ruwe
Matt Ruwe

Reputation: 3406

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.

Upvotes: 0

Views: 1420

Answers (2)

Matt Ruwe
Matt Ruwe

Reputation: 3406

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.

Upvotes: 0

rdiazv
rdiazv

Reputation: 1153

DateJS doesn't seems to support milliseconds parsing. There's the u FormatSpecifier on the DateJS extras that could work (haven't tested it).

http://code.google.com/p/datejs/wiki/FormatSpecifiers

Upvotes: 1

Related Questions