In this article, we will learn how to convert the date of one timezone to another. This can be done in two ways:
Method 1: Using Intl.DateTimeFormat() and format(): The Intl.NumberFormat() method is used to represent numbers in language-sensitive formatting. It can be used to represent currency or percentages according to the locale specified. The format() method of this object is used to return a string of the date with the specified locale and formatting options. This will format the date to the timezone required and return a string with the converted date.
Syntax:
intlDateObj = new Intl.DateTimeFormat('en-US', {
timeZone: "America/New_York"
});
usaTime = intlDateObj.format(date);
Example: In this example, we will use Intl.NumberFormat() method
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to convert date to another timezone in JavaScript ?
</title>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to convert date to another
timezone in JavaScript?
</b>
<br><br>
<button onclick="changeTimezone()">
CLick here to change an IST date to US timezone
</button>
<script type="text/javascript">
function changeTimezone() {
let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
document.write('Given IST datetime: ' + date + "<br>");
let intlDateObj = new Intl.DateTimeFormat('en-US', {
timeZone: "America/New_York"
});
let usaTime = intlDateObj.format(date);
document.write('USA date: ' + usaTime);
}
</script>
</body>
</html>
|
Output:
Method 2: Using toLocaleString() method: The toLocaleString() method is used to return a string that formats the date according to the locale and options specified. It will convert the date on which the method is used from one timezone to another.
Syntax:
usaTime = date.toLocaleString("en-US", {timeZone: "America/New_York"});
Example: In this example, we will use Using toLocaleString() method
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to convert date to another timezone in JavaScript ?
</title>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to convert date to another
timezone in JavaScript?
</b>
<br><br>
<button onclick="changeTimezone()">
Change timezone
</button>
<script type="text/javascript">
function changeTimezone() {
let date =
new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
document.write('Given IST datetime: ' + date + "<br>");
let usaTime =
date.toLocaleString("en-US", {
timeZone: "America/New_York"
});
document.write('USA datetime: ' + usaTime);
}
</script>
</body>
</html>
|
Output:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 May, 2023
Like Article
Save Article