When you are sending date information to the client as a response to an AJAX request, make sure that it's serialized to JSON, as that is an agreed upon format to exchange messages between server and client, and works very well in JavaScript. Unfortunately, JSON does not provide us with any rules for formatting dates.
In .NET you can serialize an object to JSON using the JavaScriptSerializer class. If you decide to use that, it will take care of serializing DateTime structures for you. What it will do is described in much more detail on MSDN, see: Stand-Alone JSON Serialization.
When not using ASP.NET, a DateTime type is represented in JSON as a string with a special format...
What it comes down to is this: "\/Date(700000+0500)\/"
DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc.
Note that the forward slashes are both escaped. Only in that case should the string be interpreted as a date. If not, it should just be interpreted as a string, although a rather strange one...
So how do we 'deserialize' this in JavaScript? If there is no timezone component, it can be as simple as:
var date = new Date(parseInt(value.substr(6))); // parseInt will pick up the integer value // The Date constructor understands the value as milliseconds from 1/1/1970 Or you can use eval (considered 'evil' by some) and inject some JavaScript into the value:
var date = eval("new " + value.slice(1, -1)); // effectively eval("new Date(1234567)") There's lots of questions on StackOverflow about this as well:
- Deserializing Client-Side AJAX JSON DatesDeserializing Client-Side AJAX JSON Dates (great answers here!)
- Parsing JSON DateTime from Newtonsoft's JSON SerializerParsing JSON DateTime from Newtonsoft's JSON Serializer
- Deserializing Client-Side AJAX JSON DatesDeserializing Client-Side AJAX JSON Dates
And finally a good blog post from Microsoft's Betrand Leroy which explains the rationale for .NET:
So my advice is to stick with the format that .NET will use by default and you always be able to find the correct way to handle it, even if you must handle timezones as well. Whatever you do, do not invent your own format!
PS. From ASP.NET MVC 3 you can model bind to JSON as well, so you can send JSON to controller actions as well.