How to JSON stringify a javascript Date and preserve timezone
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(); }
JSON Stringify changes time of date because of UTC
Recently I have run into the same issue. And it was resolved using the following code:
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
Json Stringify date produces a wrong date compared to javascript date
This is due to the timezone component in the Date
. The work around I did was:
var date = $(.datepicker).datepicker('getDate');
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()))
var result = Json.stringify(utcDate);
The removes the timezone component.
Why does JSON.stringify screw up my datetime object?
There is not special way to serialize Date
objects in JSON. That's why you get the standardized string representation. You need to convert them back to Date
objects by passing them to the Date
constructor.
item['created_at'] = new Date(item['created_at']);
Update: With the reviver
function (see comments), you can get the Date
objects back.
var item = JSON.parse(row, function (key, value) {
if (key === 'created_at') {
return new Date(value);
} else {
return value;
}
});
Issues with Date() when using JSON.stringify() and JSON.parse()
If you look at the output of JSON.stringify for a Date, you'll see that:
JSON.stringify(new Date())
Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.
The Date object's constructor can take a date string, so you can turn those string values back into dates by doing:
var x = new Date(JSON.parse(JSON.stringify(new Date())));
Then the arithmetic will work.
x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON date, display original date in the server's timezone
Just use the parseZone
function, like so:
moment.parseZone(s)
Documentation is here.
Alternatively, you can use the older approach, which does the same thing:
moment(s).zone(s)
Related Topics
Background-Color Hex to JavaScript Variable
Share Variables Between Files in Node.Js
Date Parsing in JavaScript Is Different Between Safari and Chrome
Is 'Window' Really Global in JavaScript
Switch Statement for String Matching in JavaScript
Differencebetween Using Constructor VS State = {} to Declare State in React Component
Sort an Array with Arrays in It by String
How to Remove an Object from an Array with JavaScript
Passing in Dynamic Key:Value Pairs to an Object Literal
Random Number Generator Without Dupes in JavaScript
Passing Python Data to JavaScript via Django
Get All User Defined Window Properties
Converting JSON Results to a Date
Jest: Timer and Promise Don't Work Well. (Settimeout and Async Function)
Getting How Many People Are in a Chat Room in Socket.Io
How Is a Promise/Defer Library Implemented
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser