Using Dates with JSON.NET

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:

Published by

Julian Birch

Full time dad, does a bit of coding on the side.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s