Skip to content

JavaScript getTime() Method and format | Examples code

  • by

JavaScript’s getTime method returns the number of milliseconds. Where A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date.

Syntax

Date.getTime()

Return Value

It returns the numeric value corresponding to the time for the specified date according to universal time.

Examples of JavaScript getTime format

Let’s see the example of return the number of milliseconds since 1970/01/01 using getTime methods in js.

<html>
   <head>
      <title>JavaScript getTime Method</title>
   </head>
   
   <body>   
      <script>
         var dt = new Date( "July 25, 2020 20:17:07" );
         alert("getTime() : " + dt.getTime() ); 
      </script>      
   </body>
</html>

Output:

JavaScript getTime Method and format

Calculate the number of years since 1970/01/01:

<html>
   
   <body>   
      <script>
         var minutes = 1000 * 60;
		var hours = minutes * 60;
		var days = hours * 24;
		var years = days * 365;
		var d = new Date();
		var t = d.getTime();

			var y = Math.round(t / years);
         alert(y); 
      </script>      
   </body>
</html>

Output: 51

How to get JavaScript to get the current time in milliseconds?

Use Date.now() to get the number of milliseconds since midnight January 1, 1970, in JavaScript.

Q: How to Javascript gettime timezone?

Answer: Get time of specific timezone, If you know the UTC offset then you can pass it and get the time using the following function:

<html>
   
   <body>   
      <script>
         function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for city"+ city +" is "+ nd.toLocaleString();
}

alert(calcTime('Bombay', '+5.5'));
      </script>      
   </body>
</html>

Output:

Javascript gettime timezone

Code source: Stackoverflow

Do comment if you have any questions, doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading