Skip to content
Related Articles

Related Articles

JavaScript Date toLocaleString() Method
  • Last Updated : 03 Jul, 2020

Below is the example of Date toLocaleString() method.

  • Example:




    <script>
        var d = new Date(Date.UTC(2020, 9, 26, 7, 0, 0));
        var result = d.toLocaleString();
        document.write("Date and Time of apocalypse: "
        + result);
    </script>                    
  • Output:
    Date and Time of apocalypse: 26/10/2020, 12:30:00

    The date.toLocaleString() method is used to convert a date and time to a string.
    Syntax:

    dateObj.toLocaleString(locales, options)

    Parameters: This methods 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 a 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 date and time as a string value in the specific format that is specified by locale.

    Note: The dateObj should be a valid Date object.



    Program 1: 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 return the result which is machine-specific.




    <script>
      var d = new Date();
      var result = d.toLocaleString();
      document.write("date and time as a string =  " + result);
    </script>
       

    Output:

    date and time as a string = 6/26/2018, 10:28:17 

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




    <script>
      var date = new Date(Date.UTC(2018, 5, 26, 7, 0, 0));  
      var options = { hour12: false };  
      document.write(date.toLocaleString("en-US"));
      document.write("<br>");
      document.write(date.toLocaleString("en-US", options));
    </script>

    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..

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

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

    full-stack-img

    My Personal Notes arrow_drop_up
Recommended Articles
Page :