Open In App

JavaScript Date getTime() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

JavaScript Date getTime() Method is used to return the number of milliseconds since 1 January 1970. When a new Date object is created it stores the date and time data when it is created. The getTime() always uses UTC for time representation.

Syntax

Date.getTime();

Parameters: This method does not accept any parameter.

Return type: A numeric value equal to no of milliseconds since Unix Epoch.

Date getTime() Method Examples

Example 1: Get time in milliseconds

This code demonstrates how to get the time in milliseconds from a Date object. It creates a Date object representing October 15, 1996, at 05:35:32. Then, it calls the getTime() method on the Date object to retrieve the time in milliseconds since January 1, 1970 (UNIX epoch). Finally, it logs the result to the console.

JavaScript
// Here a date has been assigned 
// While creating Date object 
let A = new Date('October 15, 1996 05:35:32'); 

// Hour from above is being 
// extracted using getTime() 
let B = A.getTime(); 

// Printing time in milliseconds. 
console.log(B)

Output
845357732000

Example 2: creating a Date object with an invalid date string

The code attempts to create a Date object with an invalid date string (“October 35, 1996 12:35:32”). Since the date string is invalid (October doesn’t have 35 days), the Date object creation will result in an invalid date. Consequently, getTime() will return NaN (Not-a-Number), which will be logged to the console.

JavaScript
// Creating a Date object 
let A = new Date('October 35, 1996 12:35:32'); 
let B = A.getTime();

// Printing hour. 
console.log(B); 

Output
NaN

Example 3: Calculating user age

The code calculates the age in years by subtracting the birth date (July 29, 1997) from the current date, both converted to milliseconds since the Unix epoch, and then dividing by the number of milliseconds in a year. Finally, it rounds the result using Math.round() and logs the age to the console.

JavaScript
let BD = new Date("July 29, 1997 23:15:20");
let Today = new Date();
let today = Today.getTime();
let bd = BD.getTime();
let year = 1000 * 60 * 60 * 24 * 365;
let years = (today - bd) / year;
console.log(Math.round(years));

Output
27

Supported Browsers:

We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads