JavaScript getTime() | Get 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 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 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 total milliseconds in a year, then divide that value with the value returned by getTime() method in a 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: The Math.round() round a specified number to its nearest integer value.

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

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

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

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋