JavaScript Date.now()
Syntax & Examples
Date.now() static-method
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, ignoring leap seconds. It provides a quick and efficient way to get the current timestamp in milliseconds.
Syntax of Date.now()
The syntax of Date.now() static-method is:
Date.now()
This now() static-method of Date returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
Return Type
Date.now() returns value of type Number
.
✐ Examples
1 Using Date.now() to get the current timestamp
In JavaScript, we can use the Date.now()
method to get the current timestamp in milliseconds.
For example,
- We call the
Date.now()
method to get the current timestamp. - The current timestamp is stored in the variable
currentTimestamp
. - We log
currentTimestamp
to the console usingconsole.log()
method.
JavaScript Program
const currentTimestamp = Date.now();
console.log(currentTimestamp);
Output
1625151243567
2 Calculating the difference between two timestamps
In JavaScript, we can use the Date.now()
method to calculate the difference between two timestamps.
For example,
- We get the current timestamp using
Date.now()
and store it in the variablestart
. - We simulate a delay using
setTimeout()
method with a delay of 1 second (1000 milliseconds). - After the delay, we get another timestamp using
Date.now()
and store it in the variableend
. - We calculate the difference between
end
andstart
and store it in the variableduration
. - We log
duration
to the console usingconsole.log()
method.
JavaScript Program
const start = Date.now();
setTimeout(() => {
const end = Date.now();
const duration = end - start;
console.log(`Elapsed time: ${duration} ms`);
}, 1000);
Output
Elapsed time: 1000 ms
3 Using Date.now() to measure execution time of a function
In JavaScript, we can use the Date.now()
method to measure the execution time of a function.
For example,
- We define a function
exampleFunction
that performs some operations. - We get the timestamp before the function execution using
Date.now()
and store it in the variablestart
. - We call the
exampleFunction
. - We get the timestamp after the function execution using
Date.now()
and store it in the variableend
. - We calculate the execution time by subtracting
start
fromend
and store it in the variableexecutionTime
. - We log
executionTime
to the console usingconsole.log()
method.
JavaScript Program
function exampleFunction() {
for (let i = 0; i < 1000000; i++); // Simulate some work
}
const start = Date.now();
exampleFunction();
const end = Date.now();
const executionTime = end - start;
console.log(`Execution time: ${executionTime} ms`);
Output
Execution time: 15 ms
Summary
In this JavaScript tutorial, we learned about now() static-method of Date: the syntax and few working examples with output and detailed explanation for each example.