Closed melnikaite closed 9 years ago
Date.prototype.toJSON returns a string... ISO-8601 format by default... the hydration in JSON.parse does not re-hydrate dates by default...
You can pass your own hydration as a second parameter to JSON.parse
var str = JSON.stringify(new Date()); //this is a string.
var dtm = JSON.parse(str, function(val) {
if (typeof val !== string) return val;
//new Date(ISOSTRING) requires a modern browser of ES5-shim of Date
if ((/^\d{4}\-\d\d\-\d\dT\d\d\:\d\d\:\d\d/).test(val)) return new Date(val);
return val;
})
Your best bet is to just know which fields are supposed to be date-time and translate appropriately. Also, this doesn't account for older MS Asp.Net based services, which used a different encoding for dates, this was before the more prevailant ISO-8601 utc construct became more popular. It also won't carry timezone information or offsets etc generally.
Beyond this, there is a hydrator bug with IE8 that will error and you can't catch if you have added shimmed ES5 methods to Object.prototype or Array.prototype.
Thanks for explanation I support only modern browsers, so ended up with https://jsfiddle.net/tbmf7yhx/2/
JSON.parse(JSON.stringify(new Date))
Could you please explain why I'm getting String instead of Object?
https://jsfiddle.net/tbmf7yhx/1/