Get current time in milliseconds since epoch in JavaScript
This post will discuss some of the possible ways to get the current time in milliseconds since the epoch in JavaScript.
There are several ways to get the current time since the epoch in JavaScript. The epoch is defined as the midnight at the beginning of January 1, 1970, UTC. Here are some possible functions:
1. Using Date.now() function
One way is to use the Date.now() function, which is a built-in static function that returns the number of milliseconds elapsed since the epoch. This function is compatible with strict mode and newer versions of JavaScript. For instance:
|
1 2 3 4 5 |
// get the current time in milliseconds const milliseconds = Date.now(); // print the result console.log(milliseconds); |
2. Using new Date().getTime() function
Another way is to use the getTime() function of the Date object, which is a built-in object that represents a date and time. We can create a new Date object with the current date and time, and then use the getTime() function to get the number of milliseconds since the epoch. For instance:
|
1 2 3 4 5 |
// get the current time in milliseconds const milliseconds = new Date().getTime(); // print the result console.log(milliseconds); |
3. Using new Date().valueOf() function
This is another instance function that returns the same value as Date.now(), but uses the valueOf() function that returns the primitive value of a Date object. For instance:
|
1 2 3 4 5 |
// get the current time in milliseconds const milliseconds = new Date().valueOf(); // print the result console.log(milliseconds); |
4. Using unary plus operator
Finally, we can use the unary plus operator (+) on a Date object, which is a shorthand way of converting it to a number. This will return the same result as the getTime() function. We can get the current time using this by creating a new Date object without any arguments and prefixing it with a plus sign. For instance:
|
1 2 3 4 5 |
// get the current time in milliseconds const milliseconds = +new Date(); // print the result console.log(milliseconds); |
These are some of the ways to get the current time in milliseconds since the epoch in JavaScript. We can use any of them depending on our preference and compatibility.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)