In my angular js application i got success response from web service ,and i am trying to displaying the response data in console
console.log(JSON.stringify(data))
But the problem is in my success response data has a date element .i have printed the before and after the JSON.stringify(data)
the outputs are :
before :Tue Aug 14 2012 00:00:00 GMT+0530 (India Standard Time)
after JSON.stringify(data) :"2012-08-13T18:30:00.000Z"
in after it shows 13 Aug date instead of 14 Aug date .
please tell me how can i solve this issue,i want to get 14 aug after JSON.stringify(data)
.
In my angular js application i got success response from web service ,and i am trying to displaying the response data in console
console.log(JSON.stringify(data))
But the problem is in my success response data has a date element .i have printed the before and after the JSON.stringify(data)
the outputs are :
before :Tue Aug 14 2012 00:00:00 GMT+0530 (India Standard Time)
after JSON.stringify(data) :"2012-08-13T18:30:00.000Z"
in after it shows 13 Aug date instead of 14 Aug date .
please tell me how can i solve this issue,i want to get 14 aug after JSON.stringify(data)
.
.toString
on it to get a representation of it in the local timezone, or you use .toUTCString()
to get the same representation as JSON.stringify
does.
– Bergi
Commented
Sep 12, 2014 at 11:35
JSON.stringify
uses the toJSON
method - if defined - to serialize objects. Date
objects have that method defined in their prototype
indeed, and it's pretty much equivalent to Date.prototype.toISOString
.
So a solution would be redefining Date.prototype.toJSON
: I don't really remend it, as the ISO format is pretty much conventional to transport dates as strings, but it can be done.
This example makes use of moment.js:
Date.prototype.toJSON = function() {
return moment(this).format("YYYY-MM-DD HH:mm:ss");
};
In the end, ask yourself: why should you use JSON.stringify
to display a date on the console? Date
has plenty of methods to display dates (toString
, toUTCString
, toLocaleString
, toISOString
, ... not all of them supported by every browser, to be fair), and if they don't satisfy your needs there are quite some date libraries (like moment.js mentioned above) that can help you.