mark smith mark smith - 6 months ago 57
JSON Question

JSON Stringify changes time of date because of UTC

My date objects in JavaScript are always represented by UTC +2 because of where I am located. Hence like this

Mon Sep 28 10:00:00 UTC+0200 2009


Problem is doing a
JSON.stringify
converts the above date to

2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)


What I need is for the date and time to be honoured but it's not, hence it should be

2009-09-28T10:00:00Z (this is how it should be)


Basically I use this:

var jsonData = JSON.stringify(jsonObject);


I tried passing a replacer parameter (second parameter on stringify) but the problem is that the value has already been processed.

I also tried using
toString()
and
toUTCString()
on the date object, but these don't give me what I want either..

Can anyone help me?

Answer

Recently I have run into the same issue. And it was resolved using the following code:

x = new Date();
x.setHours(x.getHours() - x.getTimezoneOffset() / 60);