Change language

JavaScript getTime

|

The getTime() method returns the number of milliseconds* since the Unix Epoch, which means that getTime returns the number of milliseconds between midnight of January 1, 1970 and the specified date. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00.

getTime () always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

The browsers supported by JavaScript Date getTime() method are listed below:

  • Google Chrome
  • Opera
  • Firefox
  • Safari
  • Internet Explorer

You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.

const moonLanding = new Date(’July 20, 69 20:17:40 GMT+00:00’);

// milliseconds since Jan 1, 1970, 00:00:00.000 GMT
console.log(moonLanding.getTime());
// expected output: -14182940000

JavaScript getTime Example

var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getTime() : " + dt.getTime() ); 

Output:

getTime() : 819922520000

JavaScript getTime Example #2

Here we will calculate the user age by providing the birth date of the user.


	var BD = new Date("July 29, 1997 23:15:20");
	var date = document.querySelector(".date");
	var time = document.querySelector(".time");
	var Today = new Date();
	var today = Today.getTime();
	var bd = BD.getTime();
	var year = 1000 * 60 * 60 * 24 * 365;
	var years = (today - bd) / year;
	date.innerHTML = BD;
	time.innerHTML = BD.getTime();
	var y = document.querySelector(".years");
	y.innerHTML = Math.round(years)

Output:

JavaScript getTime

JavaScript getTime Example #3

Here the date of the month must lie in between 1 to 31 because no date can have month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31. Hours will not have existed when the date of the month given as 33 i.e, greater than 31.

// Creating a Date object
var A = new Date(’October 35, 1996 12:35:32’);

var B = A.getTime();

// Printing hour.
document.write(B);

Output:

NaN