Date.now() function in JavaScript

JavascriptWeb DevelopmentFront End Scripts

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 now() function of the Date object returns the number of milliseconds since 1st Jan 1970.

Syntax

Its syntax is as follows

Date.now();

Example

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      var birthDate = Date.parse('29 sep 1989 00:4:00 GMT');
      document.write(currentDate);
      document.write(", "+birthDate+", ");
      document.write(currentDate - birthDate);
   </script>
</body>
</html>

Output

1537780591654, 623030640000, 914749951654

Example

You can get the current date using this function but, since it returns the nu8mber of milliseconds from 1st Jan 1970 to get the formatted date pass the value obtained to the Date constructor.

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      document.write(currentDate);
      document.write("<br>");
      document.write(Date(currentDate).toString());
   </script>
</body>
</html>

Output

1539758885099
Wed Oct 17 2018 12:18:05 GMT+0530 (India Standard Time)
raja
Published on 24-Oct-2018 15:43:28
Advertisements