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
You could get the same value by calling
new Date().getTime() or new Date().valueOf()
Note: IE8 and below do not have the
Date. Look for a polyfill if you need to support IE8 and below, or simply use
Date.nowis undefined (as that’s what a polyfill would do)
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 the the next second even if the second is not fully completed.
or, less readable:
~~(Date.now() / 1000)
I’ve seen tutorials using
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.