Open In App

JavaScript Date toLocaleString() Method

The date.toLocaleString()method is used to convert a date and time to a string using the locale settings.

Syntax:



dateObj.toLocaleString(locales, options)

Parameters: This method accepts two parameters as mentioned above and described below:

Return values: It returns date and time as a string value in the specific format that is specified by the locale.



Note: The dateObjshould be a valid Date object.

Example 1: Below is the example of the Date toLocaleString()method.




let d = new Date(Date.UTC(2020, 9, 26, 7, 0, 0));
let result = d.toLocaleString();
console.log("Date and Time of apocalypse: "+ result);

Output:

Date and Time of apocalypse: 26/10/2020, 12:30:00

Example 2:This code prints the current date and time. Also, In this code toLocaleString()method does not use any parameter so it uses the operating system’s locale’s conventions and returns a result that is machine-specific.




let d = new Date();
let result = d.toLocaleString();
console.log("date and time as a string = " + result);

Output:

date and time as a string = 1/9/2023, 1:17:10 PM

Example 3:This code prints the date and time in string format specified by the locale parameter.




let date = new Date(Date.UTC(2018, 5, 26, 7, 0, 0));
let options = { hour12: false };
console.log(date.toLocaleString("en-US"));
console.log(date.toLocaleString("en-US", options));

Output:

6/26/2018, 12:30:00 PM
6/26/2018, 12:30:00

Note: The toLocaleString()method is different from toLocaleDateString()as toLocaleDateString()converts only the date of a Date object into a string but toLocaleString()converts date and time to a string.

We have a complete list of Javascript Date methods, to check those please go through the Javascript Date Object Complete Reference article.

Supported Browsers: The browsers supported by JavaScript Date toLocaleString() Methodare listed below:


Article Tags :