Saturday, September 28, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Date toLocaleDateString() Method

JavaScript Date toLocaleDateString() Method

The date.toLocaleDateString() method converts a date to a string. 

Syntax:

dateObj.toLocaleDateString( [locales][, options])

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

  • locales: This parameter is an array of locale strings that contain one or more language or locale tags. Note that it is an optional parameter. If you want to use the specific format of the language in your application then specify that language in the locales argument.
  • Options: It is also an optional parameter and contains properties that specify comparison options. Some properties are localeMatcher, timeZone, weekday, year, month, day, hour, minute, second, etc.

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

Note: The dateObj should be a valid Date object.

Below are examples of the Date toLocaleDateString() method.

Example 1: 

Javascript




let dateObj = new Date();
let options = {
    weekday: "long",
    year: "numeric",
    month: "short",
    day: "numeric"
};
console.log(dateObj.toLocaleDateString("en-US"));
console.log(dateObj.toLocaleDateString("en-US", options));


Output:

6/24/2018
Sunday, Jun 24, 2018 

Example 2: Without parameters return value of this method cannot be relied upon in scripting. It uses the operating system’s locale conventions. 

Javascript




let dateObj = new Date(1993, 6, 28, 14, 39, 7);
console.log(dateObj.toLocaleDateString());


Output:

7/28/1993 

Note: The locales and options arguments are not supported in all browsers. To check whether it is supported or not we can use the following function :

function toLocaleDateStringSupportsLocales() {
    try {
        new Date().toLocaleDateString('i');
    }
    catch (e) {
        return e.name === 'RangeError';
    }
    return false;
}

We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.

Supported Browsers: The browsers supported by JavaScript Date toLocaleDateString() method are listed below:

  • Google Chrome
  • Internet Explorer
  • Mozilla Firefox
  • Opera
  • Safari

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

RELATED ARTICLES

Most Popular

Recent Comments