How to deserialize JSON text into a date type using Windows 8 JSON.parse?

I'm building a Windows 8 Metro app (aka "Modern UI Style" or "Windows Store app") in HTML5/JavaScript consuming JSON Web Services and I'm bumping into the following issue: in which format should my JSON Web Services serialize dates for the Windows 8 Metro JSON.parse method to deserialize those in a date type?

I tried:

  • sending dates using the ISO-8601 format, (JSON.parse returns a string),
  • sending dates such as "/Date(1198908717056)/" as explained here (same result).

I'm starting to doubt that Windows 8's JSON.parse method supports dates as even when parsing the output of its own JSON.stringify method does not return a date type.

Example:

    var d = new Date(); // => a new date
    var str = JSON.stringify(d); // str is a string => "\"2012-07-10T14:44:00.000Z\""
    var date2 = JSON.parse(str); // date2 is a string => "2012-07-10T14:44:00.000Z"

Answers


Here's how I got this working in a generic way (though it I'd rather find a format supported out-of-the-box by Windows 8's JSON.parse method):

On the server, I'm serializing my strings using:

date1.ToString("s");

This uses the ISO 8601 date format which is always the same, regardless of the culture used or the format provider supplied (see here for more information).

On the client-side, I specified a "reviver" callback to JSON.parse which looks for dates using a regexp and converts them into a date object automatically.

In the end, the deserialized object will contain actual JavaScript date types and not strings.

Here's a code sample:

    var responseResult = JSON.parse(request.responseText, function dateReviver(key, value) {
if (typeof value === 'string') {
    var re = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)$/
    var result = re.exec(value);
    if (result) {
        return new Date(Date.UTC(+result[1], +result[2] - 1, +result[3], +result[4],+result[5], +result[6]));
    }
});

Hope this helps, Carl


Need Your Help

Saving the database backup on server instead of pushing to user

php mysql codeigniter

Below is how I am generating the MySql database backup and forcing it to be downloaded on the users computer:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.