circuit

How to Initialize a JavaScript Date to a Particular Time Zone?

Sometimes, we may want to initialize a JavaScript date to a particular time zone. The default time zone is UTC.




In this article, we will look at ways to initialize a JavaScript date into a particular time zone.

Add the Time Zone to the End of the Date String

We can add the time zone info to the end of the date string that we use to create the Date object.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d)

The +08:00 part means that the date string we have is 8 hours ahead of UTC.

So d is:

Sun Apr 12 2020 09:00:00 GMT-0700 (Pacific Daylight Time)

when we’re using a device set to the Pacific time zone.

Date.prototype.toLocaleString

The JavaScrip date object has the toLocaleString method to convert a date to a date string in the given time zone.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
const dateStr = d.toLocaleString('en-US', {
  timeZone: 'America/New_York'
})
console.log(dateStr)

to do this.

We call toLocaleString on d with the locale as the first argument.

The 2nd argument is an object with the timeZone property set to 'America/New_York' so that we can return a date string in the New York time zone.

Therefore, dateStr is:

4/12/2020, 12:00:00 PM

which is the equivalent of the date and time we pass into the Date constructor in the New York time zone.

Getting the Hours

If we get the hours with getHours , then the hour returned will be the equivalent in the device’s time zone.

For instance, if we have:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d.getHours())

The time in the string is midnight.

And the time zone is UTC +8.

So if we’re in the Pacific time zone, we get 9 since it’s Daylight Saving Time so it’s 7 hours behind UTC and 15 hours behind UTC +8.

Conclusion

We can initialize a date with the given time zone by adding the time zone information to the date string we use to create the Date instance in JavaScript.




Continue Learning