My JSON string contains a date field that returns such a value:
"2009-04-04T22:55:16.0000000-04:00"
I am particularly interested in parsing only the date compartment not the time. I tried using a reviver function, but interestingly the reviver function is never invoked! (tried on Firefox)
Here is my code to accomplish that:
var Site = {
.....
dateReviver: function(key, value) {
var a;
if (typeof value === 'string') {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
},
loadArticle: function(id) {
....
proxy.getArticle(id, function(response) {
var data = JSON.parse(response.result, Site.dateReviver);
....
});
}
};
JSON.parse in loadArticle
never calls dateReviver
.
I invested a whole day but no luck! Could someone please help me?
The use of
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
does not adjust the date for the timezone information, the
-4:00
in the example.An alternative is to let Date() do the parsing for you:
If the JSON had been formatted with JSON.stringify() it would have been in UTC (Z).
Extending the jQuery.ajax converters setting worked fine for me from its's default:
to
Using TypeSript, my solution is as follows:
Best of all worlds ;-) It uses an anonymous datereviver, which gets called by JSON.parse on each property. The reviver logic is to check whether the property is of type string and if so, whether it looks like the start of a date ... If it is a date, then let new Date(value) do the actual parsing ... all timezone variations are supported that way.
Hope it helps!
The regular expression expects a "Zulu" timezone (A 'Z' character at the end), while the sample date-time string shows a numeric timezone ('-04:00'). The following regex will accept both:
If the time zone digits are not zero, you might want to actually modify the date after parsing and/or converting to UTC, to respect the timezone.
I can see dateReviver() being hit. Try the following in a browser:
I am getting the following in the browser, indicating successful parsing: