JavaScript getTime(): Get the number of milliseconds since January 1, 1970

The JavaScript getTime() method is used to get the total number of milliseconds since January 1, 1970. For example, the example given below prints the total milliseconds passed since January 1, 1970:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let msSince1970 = d.getTime();
      document.getElementById("xyz").innerHTML = msSince1970;
   </script>

</body>
</html>
Output

JavaScript getTime() syntax

The syntax of the getTime() method in JavaScript is:

x.getTime()

where x must be an object of the Date() constructor.

The getTime() method returns a number that will be the number of milliseconds since January 1, 1970.

Find the number of years since January 1, 1970, using JavaScript getTime()

You can use the getTime() method to get the total milliseconds since January 1, 1970. Now find the total milliseconds in a year, then divide that value with the value returned by the getTime() method in the way shown in the example given below:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>Year since January 1, 1970 = <span id="res"></span> Years</p>

   <script>
      const msInAnHour = 1000*60*60;
      const msInADay = msInAnHour*24;
      const msInAYear = msInADay*365;
      
      const d = new Date();
      let msSince1970 = d.getTime();

      const yearSince1970 = msSince1970/msInAYear;
      
      document.getElementById("res").innerHTML = Math.round(yearSince1970);
   </script>

</body>
</html>
Output

Year since January 1, 1970 = Years

Please note: Math.round() rounds a specified number to its nearest integer value.

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!