Home > Enterprise >  Wrong Time Zone Offset Returned by Javascript Date object
Wrong Time Zone Offset Returned by Javascript Date object

Time:12-08

I am using the following code to get a datetime at a specified time zone. The date and time is returned correctly except for the the time zone offset.

Ex: in the below snippet it returns time zone offset (GMT 2) instead of the desired one (GMT 5 at New Delhi)

How to fix it to return the same offset as the specified time zone?

const options = {
  dateStyle: "long",
  timeStyle: "long",
};

const dateTimeAtNewDelhi = new Date(new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata" }))
 
 
document.querySelector('#timezone-date-time').innerHTML = dateTimeAtNewDelhi.toLocaleString("en-US", options);
 
#timezone-date-time{
  font-size:1.5em;
  margin:auto;
}
<div id="timezone-date-time">

</div>

CodePudding user response:

In your attempt to create dateTimeAtNewDelhi, it would appear that you are expecting the Date object to retain the time zone. It will not.

The Date object does not carry any time zone information with it whatsoever. It is simply a wrapper around the number of milliseconds since 1970-01-01 00:00:00.000 UTC.

Thus, the way you fix it, is by specifying the time zone during output.

const options = {
  dateStyle: "long",
  timeStyle: "long",
  timeZone: "Asia/Kolkata"
};

const dateTime = new Date();
 
 
document.querySelector('#timezone-date-time').innerHTML = dateTime.toLocaleString("en-US", options);
 
#timezone-date-time{
  font-size:1.5em;
  margin:auto;
}
<div id="timezone-date-time">

</div>

Note that your original approach tried re-parsing to account for time zone, which is a common mistake, covered in this answer - along with other approaches that do work, such as using a time zone aware object from a library, rather than Date.

  • Related