JustLearning JustLearning -4 years ago 208
Javascript Question

Json Stringify date produces a wrong date compared to javascript date

When i create a

date and then
it and send it to the server, i get two different dates. The
date is always one day behind.

So currently i increment my
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download