JavaScript Date.now()

Posted by

Introduction to JavaScript Date.now()

The JavaScript Date.now() method is a static method available on the Date object. It returns the time in milliseconds since January 1, 1970 00:00:00 UTC (12 AM UTC). It is often used to measure the time elapsed since the start of a process, or to generate unique IDs.

Syntax

The syntax for the Date.now() method is:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

Date.now()

[/dm_code_snippet]

Example

Let’s look at an example of how to use the Date.now() method.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let startTime = Date.now();

// do something

let endTime = Date.now();
let elapsedTime = endTime - startTime; // in milliseconds
console.log(elapsedTime);

[/dm_code_snippet]

In the above example, we measure the time elapsed between the start and end of a process. We store the start time in the startTime variable, execute some code, and then store the end time in the endTime variable. Finally, we subtract the start time from the end time to calculate the elapsed time in milliseconds.

Browser Support

The Date.now() method is supported in all modern browsers including Chrome, Firefox, Edge, Safari, and Opera.

Conclusion

In this tutorial, we learned about the Date.now() method and how to use it to measure the time elapsed since the start of a process, or to generate unique IDs.