2

I want

JSON.stringify(new Date()); 

to return local date. How can I do that?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Piyush
  • 599
  • 1
  • 7
  • 16

1 Answers1

3

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;
}));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875