How to Get the Current Timestamp in JavaScript
Discover the different methods JavaScript provides for generating the current UNIX timestamp.
The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1, 1970.
On UNIX-like machines, such as Linux and macOS, you can easily find the UNIX timestamp by typing date +%s
in the terminal:
1 | $ date +%s |
In JavaScript, the current timestamp can be obtained by calling the now()
method on the Date
object:
1 | Date.now() |
The same result can be achieved by using:
1 | new Date().getTime() |
However, it’s important to note that the now()
method is not available in IE8 and below. If you need to support those browsers, you can either look for a polyfill or use new Date().getTime()
.
In JavaScript, the timestamp is expressed in milliseconds. If you want to get the timestamp in seconds, you can convert it using the following code:
1 | Math.floor(Date.now() / 1000) |
It’s worth mentioning that some tutorials may suggest using Math.round()
, but this approximation rounds up to the next second even if the current second is not fully completed.
Alternatively, you can use a less readable approach with bitwise operators:
1 | ~~(Date.now() / 1000) |
Another unconventional method is to use the unary operator +
in combination with new Date
. This automatically calls the valueOf()
method on the object and returns the timestamp in milliseconds. However, keep in mind that this method creates a new Date object that is immediately discarded.
To generate a date from a timestamp, you can use new Date(<timestamp>)
. Just make sure to pass a number as a parameter, as using a string will result in an “invalid date” output (parseInt()
can be used for conversion if needed).
tags: [“JavaScript”, “programming”, “UNIX timestamp”, “Date object”, “timestamp conversion”, “milliseconds”, “seconds”]