Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
mark smith Avatar asked Sep 28 '09 11:09

mark smith


People also ask

Does JSON Stringify convert date to UTC?

JSON Stringify changes time of date because of UTC.

How do you format a date in UTC?

Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.

How can I get only the date from UTC?

JavaScript Date getUTCDate() getUTCDate() returns the day of the month (1 to 31) of a date object. getUTCDate() returns the day according to UTC.

Is it bad to use JSON Stringify?

It`s ok to use it with some primitives like Numbers, Strings or Booleans. As you can see, you can just lose unsupported some data when copying your object in such a way. Moreover, JavaScript won`t even warn you about that, because calling JSON. stringify() with such data types does not throw any error.


2 Answers

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); 
like image 173
Anatoliy Avatar answered Sep 19 '22 05:09

Anatoliy


JSON uses the Date.prototype.toISOString function which does not represent local time -- it represents time in unmodified UTC -- if you look at your date output you can see you're at UTC+2 hours, which is why the JSON string changes by two hours, but if this allows the same time to be represented correctly across multiple time zones.

like image 21
olliej Avatar answered Sep 22 '22 05:09

olliej