Converting a date to another timezone in JavaScript allows you to display the same date and time according to a different timezone. JavaScript provides built-in methods such as Intl.DateTimeFormat() and toLocaleString() for timezone-based date formatting.
The following approaches can be used to convert a date to another timezone:
Approach 1: Using Intl.DateTimeFormat() and format() Methods
The Intl.DateTimeFormat() method formats a date according to a specified locale and timezone. By providing the timeZone option, the date can be displayed according to the desired timezone.
Syntax:
const intlDateObj = new Intl.DateTimeFormat('en-US', {
timeZone: "America/New_York"
});
const usaTime = intlDateObj.format(date);
let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
console.log('Given UTC datetime: ', date);
let intlDateObj = new Intl.DateTimeFormat('en-US', {
timeZone: "America/New_York"
});
let usaTime = intlDateObj.format(date);
console.log('USA date: ', usaTime);
Output
Given UTC datetime: 2012-12-20T03:00:00.000Z USA date: 12/19/2012
Approach 2: Using toLocaleString() Method
The toLocaleString() method can format a date according to a specified locale and timezone. The timeZone option determines the timezone in which the date and time are displayed.
Syntax
const usaTime = date.toLocaleString("en-US", {
timeZone: "America/New_York"
});
let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
console.log('Given UTC datetime: ', date);
let usaTime = date.toLocaleString("en-US", {
timeZone: "America/New_York"
});
console.log('USA datetime: ', usaTime);
Output
Given UTC datetime: 2012-12-20T03:00:00.000Z USA datetime: 12/19/2012, 10:00:00 PM