An Introduction to JavaScript Object Notation (JSON) / Page 2 | WebReference

An Introduction to JavaScript Object Notation (JSON) / Page 2

[previous] [next]

An Introduction to JavaScript Object Notation (JSON) [con't]

Working with Dates

There's no doubt that JSON offers some tangible benefits over XML for Web developers, but being a fairly new initiative, there will be many wrinkles to iron out over the course of upcoming releases.

At this time, one such wrinkle is date handling. As we saw in the supported data types, dates are not one of them. The cause of this deficiency is the lack of a date literal in JavaScript. Unlike Arrays and Strings, which are actually objects, and not primitive data types, dates have to be constructed using the new keyword or by calling a function that returns a Date object. Obviously, disregarding dates is not a viable solution, so we need a way to represent them using JSON. Fortunately, there's hope.

Some resourceful developers have proposed some workarounds until the time that dates are added to the JSON standard. One particularly good one was achieved by Nikhil Kothari for a work project. He serialized the date as a string with the easily identifiable "@" character; so an object with a currentDate property would get serialized as: { "currentDate": "@1163531522089@" } The number in between the "@" characters is the number of milliseconds since Jan 1st 1970 in normalized Universal Coordinated Time (UTC).

This format works well because that's how computers store dates internally. Locale and formatting issues can be the source of many headaches; using the internal form is the best way to avoid these pitfalls. Here are some JavaScript functions that can assist you in creating a JSON-compatible date:

getTime() - The number of milliseconds since January 1, 1970. This function converts a Date object to a millisecond value:

parse() - The number of milliseconds after midnight January 1, 1970 till the given date, expressed as a string:

UTC() - Based on a comma delimited string, the number of milliseconds after midnight January 1, 1970 GMT is returned. The syntax of the string is "year, month, day [, hrs] [, min] [, sec]". The hours, minutes, and seconds are optional:

You'll have to modify your decoding function to handle the conversion of the date string back to a Date object. The encoding function can deal with it without modification because it already knows how to handle strings. Here's an example of JavaScript ASP that parses the JSON object string for date types:

The code above uses a regular expression to test for a date-formatted string. If a match is found, the number between the parentheses is converted to a true Date type using the Date(milliseconds) constructor. One caveat of using this solution is you have to be certain that you'll never get a string in the same format as your dates! A more elaborate workaround may be required than the one presented here.

[previous] [next]