The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when directly calling ASP.NET AJAX web services and page methods. Unlike every other data type in the language, JavaScript offers no declarative method for expressing a Date. Consequently, embedding them within JSON requires a bit of fancy footwork.
I will attempt to explain what exactly the problem is with dates in JSON.
What’s the problem?
The fundamental problem is that JavaScript does not provide a way to declaratively express Date objects. You may previously have seen this described as (the lack of) a Date literal. What are literals? To illustrate, these are literals for several other data types:
// String
'foo';
// Number
3.14;
// Boolean
true;
// Array
[1, 2, 3, 5, 7];
// Object
{ pi: 3.14, phi: 1.62 };
Unfortunately, when it comes to dates, the lack of a literal means that the only way to create one is by explicitly initializing a Date object:
// Correct.
new Date('4/26/09');
// Correct (the month is 0 indexed, hence the 3).
new Date(2009, 3, 26);
// Incorrect. This is a string, not a Date.
'4/26/09';
While this limitation is fine when writing client-side JavaScript code, it leaves us without a good way to transmit dates within JSON objects. lack of a date literal is a problem, Can Somebody Suggest a Solution.