To convert a date to another time zone in JavaScript:
- Use the
toLocaleString()
method of theDate
object to get a string in the provided time zone. - Pass the returned string to the
Date()
constructor. - The
Date()
constructor will return a new instance ofDate
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:
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.options
— An object where you can set some properties to customize the output format. One such property istimeZone
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
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.