JavaScript Date toLocaleString() Method



The Date.toLocaleString() method in JavaScript is used to convert a Date object to a string, representing the date and time in a locale-specific format, based on the current locale settings.

Syntax

Following is the syntax of JavaScript Date toLocaleString() method −

toLocaleString(locales, options);

Parameters

This method accepts two parameters. The same is described below −

  • locales (optional) − A string or an array of strings that represents a BCP 47 language tag, or an array of such strings. It specifies one or more locales for the date formatting. If the locales parameter is undefined or an empty array, the default locale of the runtime is used.
  • options (optional) − An object that allows you to customize the formatting. It can have properties like weekday, year, month, day, hour, minute, second, etc., depending on whether you are formatting a date or time.

Return value

This method returns the Date object as a string, using locale settings.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Date toLocaleString() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const formattedDate = currentDate.toLocaleString();

   document.write(formattedDate);
</script>
</body>
</html>

Output

It returns a Date object as a string, using locale settings.

Example 2

Here, we are using the toLocaleString() method with specific options to format the date according to the long weekday, year, month, and day in English (United States) locale.

<html>
<body>
<script>
   const currentDate = new Date();
   const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
   const formattedDate = currentDate.toLocaleString('en-US', options);

   document.write(formattedDate);
</script>
</body>
</html>

Output

As we can see in the output, it displays the date according to the specified format.

Example 3

In this example, we are customizing the time format to display hours, minutes, and seconds in a 12-hour clock with leading zeros for single-digit values.

<html>
<body>
<script>
   const currentDate = new Date();
   const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
   const formattedDate = currentDate.toLocaleString('en-US', options);

   document.write(formattedDate);
</script>
</body>
</html>

Output

As we can see in the output, it displays the date in 12 hour clock format.

Advertisements