Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JSON stringify a javascript Date and preserve timezone

I have a date object that's created by the user, with the timezone filled in by the browser, like so:

var date = new Date(2011, 05, 07, 04, 0, 0); > Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time) 

When I stringify it, though, the timezone goes bye-bye

JSON.stringify(date); > "2011-06-06T18:00:00.000Z" 

The best way I can get a ISO8601 string while preserving the browser's timezone is by using moment.js and using moment.format(), but of course that won't work if I'm serializing a whole command via something that uses JSON.stringify internally (in this case, AngularJS)

var command = { time: date, contents: 'foo' }; $http.post('/Notes/Add', command); 

For completeness, my domain does need both the local time and the offset.

like image 957
XwipeoutX Avatar asked Jun 28 '15 04:06

XwipeoutX


People also ask

Does JSON Stringify convert date to UTC?

JSON Stringify changes time of date because of UTC.

How do I Stringify a new date?

stringify changes time of date because of UTC with JavaScript, we can use JSON. parse to convert the date back to its original format. let currentDate = new Date(); currentDate = JSON. stringify(currentDate); currentDate = new Date(JSON.

Can JavaScript handle date and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.

Does JSON Stringify preserve functions?

To be clear, the output looks like JSON but in fact is just javascript. JSON. stringify works well in most cases, but "fails" with functions.


1 Answers

Assuming you have some kind of object that contains a Date:

var o = { d : new Date() }; 

You can override the toJSON function of the Date prototype. Here I use moment.js to create a moment object from the date, then use moment's format function without parameters, which emits the ISO8601 extended format including the offset.

Date.prototype.toJSON = function(){ return moment(this).format(); } 

Now when you serialize the object, it will use the date format you asked for:

var json = JSON.stringify(o);  //  '{"d":"2015-06-28T13:51:13-07:00"}' 

Of course, that will affect all Date objects. If you want to change the behavior of only the specific date object, you can override just that particular object's toJSON function, like this:

o.d.toJSON = function(){ return moment(this).format(); } 
like image 71
Matt Johnson-Pint Avatar answered Sep 20 '22 22:09

Matt Johnson-Pint