Json Stringify date produces a wrong date compared to javascript date

JustLearning picture JustLearning · Aug 26, 2016 · Viewed 7.8k times · Source

When i create a javascript date and then stringify it and send it to the server, i get two different dates. The stringified date is always one day behind.

So currently i increment my javascript date by 1 day so that i receive the same date on the server.

my current code:

var dt = $(.datepicker).datepicker('getDate');//Fri Aug 26 2016 00:00:00 GMT+0200 (South Africa Standard Time)
var result = Json.stringify(dt); //"2016-08-25T22:00:00.000Z"

Is this the correct approach or am i missing something?

Answer

Arun Ghosh picture Arun Ghosh · Aug 26, 2016

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.