How to get the current timestamp in JavaScript
Find out the ways JavaScript offers you to generate 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, which include Linux and macOS, you can type date +%s in the terminal and get the UNIX timestamp back:
$ date +%s
1524379940
The current timestamp can be fetched by calling the now() method on the Date object:
Date.now()
You could get the same value by calling
new Date().getTime()
or
new Date().valueOf()
Note: IE8 and below do not have the
now()method onDate. Look for a polyfill if you need to support IE8 and below, or usenew Date().getTime()ifDate.nowis undefined (as that’s what a polyfill would do)
The timestamp in JavaScript is expressed in milliseconds.
To get the timestamp expressed in seconds, convert it using:
Math.floor(Date.now() / 1000)
Note: some tutorials use
Math.round(), but that will approximate to the next second even if the second is not fully completed.
or, less readable:
~~(Date.now() / 1000)
I’ve seen tutorials using
+new Date
which might seem a weird statement, but it’s perfectly correct JavaScript code. The unary operator + automatically calls the valueOf() method on any object it is assigned to, which returns the timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object that’s immediately discarded.
To generate a date from a timestamp, use new Date(<timestamp>) but make sure you pass a number (a string will get you an “invalid date” result - use parseInt() in doubt)
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.