This article will provide some easy methods for initializing the JavaScript date to a particular time zone.
Different Ways of Initializing JavaScript Date to a Particular Time Zone
In JavaScript, you can use the following methods for initializing JavaScript date to a particular time zone:
Have a look at each of the mentioned approaches one by one!
Method 1: Using “toLocaleString()” Method to Initialize JavaScript Date to a Particular Time Zone
This method involves the use of the “Date” object with the “toLocaleString()” method to initialize the date to the specified time zone.
Syntax
Here, the date represents the Date object which will be used to call the “toLocaleString()” method by passing the “locales” and “options” argument, which will contain the time zone information.
Let’s overview the following example for a clear understanding.
Example
First, we will create a new Date object and store the following values (Year as “2022”, Month as “8”, Day as “23”, Hour as “8”, “0” Minutes, and “0” Seconds) respectively. Then, we will display the set date value using the “console.log()” method:
Next, we will initialize the date to “UK” time zone using “toLocaleString” method and pass “en-GB” as English Great Britain locales, and “Europe/London” as time zone:
As a result, we will get the following output:
Method 2: Using “Intl.DateTimeFormat()” Method to Initialize JavaScript Date to a Particular Time Zone
In JavaScript, the “Intl” class offers a “DateTimeFormat()” method that is used to format the date-time strings. This method performs the conversion to the specified time zone “UK“.
Let’s overview the following example for understanding the above concept clearly.
Example
Firstly, we will create a Date class object and set the values as in the previous example like (Year, Month, Day, Hours, Minutes, and Seconds) respectively and display the current date with the time zone information:
Next, we will create a new Intl object named “currentTZ”, and use the DateTimeFormat() method to initialize it to the particular time zone. Lastly, display the date with the timezone information on the console:
var ukDate = currentTZ.format(date);
console.log('Date in UK is : ', ukDate);
The output of the above-given program will be displayed as follows:
We have provided the simplest methods for initializing JavaScript date to a particular time zone.
Conclusion
To initialize JavaScript Date to a Particular Time Zone, you can use the “toLocaleString()” method for direct initialization or the “Intl.DateTimeFormat()” method, which utilizes an “Intl” class object and “DateTimeFormat()” method collectively for the mentioned purpose. However, both methods work efficiently. This article assisted regarding the procedure of initializing the JavaScript date to a particular time zone.