![]() |
VOOZH | about |
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.
Date.getTime();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.
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.
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.