I want
JSON.stringify(new Date());
to return local date. How can I do that?
I want
JSON.stringify(new Date());
to return local date. How can I do that?
The best way to handle this is to write a replacer function and pass that to JSON.stringify
. The replacer would detect dates and output the format you want for them.
JSON.stringify(new Date(), function(key, value) {
var rawValue = this[key];
if (rawValue instanceof Date) {
return /*...whatever format you want using `rawValue`...*/;
}
return value;
});
There I've made it an inline function, but of course you can make it a named function that you reuse.
Example:
console.log(JSON.stringify(new Date(), function(key, value) {
var rawValue = this[key];
if (rawValue instanceof Date) {
return "Your string here for " + rawValue;
}
return value;
}));