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?
JSON Stringify changes time of date because of 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.
JavaScript Date getUTCDate() getUTCDate() returns the day of the month (1 to 31) of a date object. getUTCDate() returns the day according to UTC.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With