JustLearning JustLearning - 3 months ago 19
Javascript Question

Json Stringify date produces a wrong date compared to javascript date

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

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.

Comments