Open In App

How to Get Milliseconds in JavaScript?

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, you can get the current time in milliseconds, which is useful for timestamping events, measuring time intervals, and performing time calculations. JavaScript provides various methods to precisely measure time down to the millisecond, including Date.now(), performance.now(), and the Date object's getTime() method. These tools enable developers to effectively manage time in their programming tasks.

These are the following methods to get milliseconds in JavaScript:

Using Date Object

In JavaScript, you can easily get the milliseconds by creating a new Date object and using its getMilliseconds() method, which generates the milliseconds part of the current time. This straightforward approach makes accessing time information for developers easier.

Example: To illustrate a new Date object using getMilliseconds() method.

JavaScript
function getCurrentMilliseconds() {
    const now = new Date();
    return now.getMilliseconds();
}

function main() {
    const milliseconds = getCurrentMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 984

Using Performance API

The Performance API gives an accurate way to measure time. Its now() method tells the current time very precisely, useful for checking performance or comparing speeds.

Example: To demonstrate how to use JavaScript's Performance API to obtain the current time in milliseconds.

JavaScript
function getPerformanceMilliseconds() {
    return performance.now();
}

function main() {
    const milliseconds = getPerformanceMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 48.6021290011704

Using Date.now() method

You can quickly get the current time in milliseconds using the Date class's now() method. It's a direct way to get accurate time information whenever you require it.

Example: To illustrate how to utilize JavaScript's Date.now() method to retrieve the current time in milliseconds.

JavaScript
function getCurrentMilliseconds() {
    return Date.now();
}

function main() {
    const milliseconds = getCurrentMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 1719817895151

Next Article

Similar Reads