JavaScript Date getTime()
Syntax & Examples
Date.getTime() method
The getTime() method of the Date object in JavaScript returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. Negative values are returned for prior times.
Syntax of Date.getTime()
The syntax of Date.getTime() method is:
getTime()
This getTime() method of Date returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
Return Type
Date.getTime() returns value of type Number
.
✐ Examples
1 Using getTime() to get the milliseconds of a specific date
In JavaScript, we can use the getTime()
method to get the number of milliseconds since January 1, 1970, 00:00:00 UTC from a Date object.
For example,
- We create a new Date object
date
representing January 15, 2021, at 15:30:00. - We use the
getTime()
method to get the milliseconds fromdate
. - The milliseconds are stored in the variable
milliseconds
. - We log
milliseconds
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2021-01-15T15:30:00');
const milliseconds = date.getTime();
console.log(milliseconds);
Output
1610721000000
2 Using getTime() with the current date
In JavaScript, we can use the getTime()
method to get the current number of milliseconds since January 1, 1970, 00:00:00 UTC from the current date.
For example,
- We create a new Date object
now
representing the current date and time. - We use the
getTime()
method to get the current milliseconds fromnow
. - The current milliseconds are stored in the variable
currentMilliseconds
. - We log
currentMilliseconds
to the console usingconsole.log()
method.
JavaScript Program
const now = new Date();
const currentMilliseconds = now.getTime();
console.log(currentMilliseconds);
Output
1622461330000
3 Using getTime() with a specific date in the past
In JavaScript, we can use the getTime()
method to get the number of milliseconds since January 1, 1970, 00:00:00 UTC from a specific date in the past.
For example,
- We create a new Date object
pastDate
representing July 4, 1776, at 12:00:00. - We use the
getTime()
method to get the milliseconds frompastDate
. - The milliseconds are stored in the variable
pastMilliseconds
. - We log
pastMilliseconds
to the console usingconsole.log()
method.
JavaScript Program
const pastDate = new Date('1776-07-04T12:00:00');
const pastMilliseconds = pastDate.getTime();
console.log(pastMilliseconds);
Output
-6106060800000
Summary
In this JavaScript tutorial, we learned about getTime() method of Date: the syntax and few working examples with output and detailed explanation for each example.