This blog will discuss the implementation of the JavaScript toLocaleString method. So, let’s start!
What is JavaScript toLocaleString() Method?
The “toLocaleString()” method gives a number as a string using the local language format. This method uses the “Date” object to initialize the date to the specific time zone.
How to Use JavaScript toLocaleString() Method?
To use the toLocaleString() method, follow the provided syntax:
In the above syntax, “date” represents the variable holding the Date object, “locales” are the various time zones, and “options” refer to the object with formatting options.
Let’s check out the following example for understanding clearly.
Example 1: Displaying Current Date and Time of Current Timezone
In the following example, create a date object with the help of the new “Date()” constructor:
Now, apply the toLocaleString() method to the date object to display the current date and time:
console.log(currdateTime);
The output of the above demonstration will be as follows:
To get the date and time of a specific time zone, implement the following example.
Example 2: Getting Date and Time of a Specific Timezone
First, create a Date object and store the values such that (Year:2022, Month:8, Day:23, Hour:8, 0 Minutes, and 0 Seconds), respectively, and display them. Here, “UTC” represents the Coordinated Universal Time according to which the world regulates clocks and time:
console.log("The date and time in UK is:", date);
Finally, display the set date value with respect to the “US” timezone using the toLocaleString() method:
Output
Example 3: Displaying Specified Date and Time by Setting their Attribute Values
Now, assign some values for the date attributes(year, month, day) and a weekday as well to be displayed along with the date:
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
Lastly, log the current date along with the weekday in “US” time zone as follows:
Output
This write-up has explained the different techniques to implement the toLocaleString() method.
Conclusion
The “toLocaleString()” method can be applied to display the current date and time with the help of the created constructor. Moreover, it can be used to initialize a particular date and time and convert it to the specified time zone or display the specified date and time by setting their attribute values along with the weekday. This blog explained the techniques to utilize the toLocaleString() method in multiple ways.