Using Dates with JSON.NET

Friday, April 17, 2009 7:03 PM

If you're using JSON.NET (and if you're using Microsoft's libraries, you really need to start) you may have run into the way it serializes dates.  Basically, for good reasons, it returns Dates in the format "\/Date(1198908717056+1200)\/".  This, of course, requires you to actually parse the date yourself, which is a bit painful, especially since you need to worry about time zones.

function parseJsonDate(jsonDate) {
    var safeDate = jsonDate.match(/([0-9]+)([+-])([0-9][0-9])([0-9][0-9])/);
    var minutes = parseInt(safeDate[3]) * 60 + parseInt(safeDate[4]);
    var offset = minutes * 60 * 1000 * parseInt(safeDate[2] + "1");
    var result = new Date(parseInt(safeDate[1]) + offset);
    var offset = result.getTimezoneOffset();
    return result;
}

This is obviously ugly, but it's getting me the right results.  However, if anyone find any bugs, please let me know.

Technorati Tags:
Comments
No comments posted yet.
Something to add?

Talking sense? Talking rubbish? Something I'm missing? Let me know!

Fields denoted with a "*" are required.

 (will not be displayed)

 
Please add 8 and 3 and type the answer here:

Preview Your Comment