A time zone belongs to the region that follows a standard local time recognized by law throughout the nation. Some countries have their own time zone, and some countries, such as the United States or Canada, even have several time zones. On a web page, developers may need to convert dates from one time zone to any other specified time zone for different purposes.
This post will describe the method for converting a date to any other specified time zone using JavaScript.
How to Convert a Date to Another Specified Time Zone Using JavaScript?
To convert a date to another timezone, use the given methods:
- toLocaleString() method
- format() method
Let’s discuss these methods in detail!
Method 1: Convert a Date to Another Time Zone Using toLocaleString() Method
For converting the date to any specified time zone, use the “toLocaleString()” method. It will change the date from one timezone to another. The toLocaleString() method returns a string that converts the date based on the locale and parameters passed in.
Syntax
Follow the given syntax for the “toLocaleString()” method to convert the date to another timezone:
Example
First, create a new date object using the Date() constructor that returns the current date, and stores it in a variable “date”:
Print the current date on the console:
Call the “toLocaleString()” method to convert the date to “America/New_York” timezone and store the resultant date and time in variable “timeZoneUSA”:
var timeZoneUSA = date.toLocaleString(“en-US”, {timeZone: “America/New_York”});
Print the resultant date in the “America/New_York” timezone on the console:
The output indicates that the date is successfully converted to the specified timeZone:
Method 2: Convert a Date to Another Time Zone Using format() Method
Another way to convert the date to another time zone is the “format()” method. It converts one time zone to another.
Syntax
The following syntax is used for the format() method:
Example
First, call the “Intl.DateTimeFormat” object to set the timezone in which the date will be converted into that timezone as it enables language-sensitive date and time formatting. Here, we will convert the date to the “America/New_York” timezone:
Then, call the format() method with the specified timezone and “date” as a parameter:
Print the resultant converted timezone on the console:
Output
We have gathered all the necessary information related to the conversion of a Date object to another timezone in JavaScript.
Conclusion
For conversion of Date to any other timezone, use the “toLocaleString()” method or the “format()” method. Both methods return the string of the date into the specified timezone. This post described the methods for converting the current date to any other specified time zone using JavaScript.