I\'m taking my first crack at Ajax with jQuery. I\'m getting my data onto my page, but I\'m having some trouble with the JSON data that is returned for Date data types. Basi
In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:
(function () {
var DATE_START = "/Date(";
var DATE_START_LENGTH = DATE_START.length;
function isDateString(x) {
return typeof x === "string" && x.startsWith(DATE_START);
}
function deserializeDateString(dateString) {
var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
return utcDate;
}
function convertJSONDates(key, value) {
if (isDateString(value)) {
return deserializeDateString(value);
}
return value;
}
window.jQuery.ajaxSetup({
converters: {
"text json": function(data) {
return window.JSON.parse(data, convertJSONDates);
}
}
});
}());
I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date
object that has the proper ticks value to reflect this. That is, calling getUTCHours()
, etc. on the date will return the same value as it did on the server, and calling getHours()
will return the value in the user's local timezone as determined by their browser.
This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.