JavaScript toLocaleDateString(): Get Date as a String using Locale Conventions

The JavaScript toLocaleDateString() method is used to get the date (using the locale conventions) as a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let dateLocale = d.toLocaleDateString();
      document.getElementById("xyz").innerHTML = dateLocale;
   </script>

</body>
</html>
Output

In the above example, in between the "script" tag where I have written the three JavaScripts, I start by creating a new "Date" object using the following code:

const d = new Date();

Then it calls the toLocaleDateString() method on the Date object to get the current date in the user's local time zone in a human-readable format.

The resulting string is then assigned to the dateLocale variable using

let dateLocale = d.toLocaleDateString();

Finally, the value of dateLocale is displayed on the webpage by updating the innerHTML of an HTML element with the ID of xyz using

document.getElementById("xyz").innerHTML = dateLocale;

Please note: In the above date, the first value represents the month number of the year, the second value represents the day of the month, and the last value represents the year.

JavaScript toLocaleDateString() syntax

The syntax of the toLocaleDateString() method in JavaScript is:

x.toLocaleDateString()

where x must be an object of the Date() constructor.

The toLocaleDateString() method returns a string, which will be the date using the locale conventions.

Please note: To get the time based on local settings, use toLocaleTimeString().

Please note: To get the complete date based on local settings, use toLocaleString().

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!