Computer >> Computer tutorials >  >> Programming >> Javascript

Date.toLocaleString() function in JavaScript


The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

The toLocaleString() function of the date object returns the date of the current date (including time).

Syntax

Its Syntax is as follows

dateObj.toLocaleString()

Example

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 89 12:4:25:96');
      document.write("Current Date: "+dateObj.toLocaleString());
   </script>
</body>
</html>

Output

Current Date: 9/26/1989, 12:04:25 PM

Example

If you do not pass anything to the constructor of the date object this functions takes the current date of the system and returns its string format.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 89 12:4:25:96');
      document.write("Current Date: "+dateObj.toLocaleString());
   </script>
</body>
</html>

Output

Current Date: 26/09/1989, 12:04:25 PM

Example

You can also specify the required format of the string by passing as a string parameter to this function.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 89 12:4:25:96');
      document.write("Current Date: "+dateObj.toLocaleString("en-us"));
   </script>
</body>
</html>

Output

Current Date: 9/26/1989, 12:04:25 PM