samedi 27 juin 2015

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.

1 commentaire: