Tutorialspoint.dev

JavaScript | date.toLocaleString()

The date.toLocaleString() is an inbuilt function in JavaScript which is used to convert a date and time to a string.
Syntax:

dateObj.toLocaleString(locales, options)

dateObj should be a valid Date object.

    Parameters:

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

JavaScript code to show the working of date.toLocaleDateString() function:



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

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

Output:

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

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

<!DOCTYPE html>
<html>
<head>
  <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>
</head>
<body></body>
</html>

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



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter