How to convert a date to another time zone in JavaScript

published: 21 Aug 2022

2 min read

How to convert a date to another time zone in JavaScript

To convert a date to another time zone in JavaScript:

  1. Use the toLocaleString() method of the Date object to get a string in the provided time zone.
  2. Pass the returned string to the Date() constructor.
  3. The Date() constructor will return a new instance of Date with its date and time set according to the provided time zone.
const convertTimeZone = (date, timeZone) => {
  return new Date((typeof date === 'string' ? new Date(date) : date)
            .toLocaleString('en-US', { timeZone }))
}

const date = new Date()
console.log(date)
// Tue Sep 13 2022 23:03:22 GMT+0500 (Pakistan Standard Time)

// => Convert to PST time zone
const pstDate = convertTimeZone(date, 'America/Los_Angeles')
console.log(pstDate)
// Tue Sep 13 2022 11:19:31

// => Convert to EU time zone
const euDate = convertTimeZone(date, 'Europe/Berlin')
console.log(euDate)
// Tue Sep 13 2022 20:21:19

The convertTimeZone() method we created above accepts either a Date object or a string as the first parameter and a time zone string as the second parameter. It returns a Date object with the date and time adjusted according to the provided time zone.

The toLocaleString() method returns a date object as a string, using the given locale settings. Under the hood, it calls the Intl.DateTimeFormat API to format the Date object to a string.

The toLocaleString() method accepts two parameter:

  1. locales - A string with a BCP 47 language tag or an array of such strings, for example, en-US (US English), en-GB (British English), de-DE (German), etc.
  2. options - An object where you can set some properties to customize the output format. One such property is timeZone which specifies the time zone to use. Read MDN docs to learn about all available options.

Here is another example that uses toLocaleString() to convert the current date to a string in the PST time zone:

const date = new Date()

const pstTime = date.toLocaleString('en-US',
  timeZone: 'America/Los_Angeles',
  dateStyle: 'full',
  timeStyle: 'full'
})

console.log(pstTime)
// Tuesday, September 13, 2022 at 11:50:57 AM Pacific Daylight Time

How to convert a date to another time zone in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array