- The leap seconds are ignored
Okay. Let’s do it step by step.
const jsTimestamp = Date.now(); const jsTimestamp = new Date().getTime(); const jsTimestamp = new Date().valueOf();
new Date()returns a
Dateobject that represents the date and time of instantiation.
Date.prototype.valueOf()are supported in IE8 and below, but
Date.prototype.valueOf()if possible due to the clarity of the code.
Need more ways to get the current timestamp?
const jsTimestamp = +new Date(); // or even ... const jsTimestamp = +new Date;
Let me explain.
plus operator calls the
Step #2: Convert milliseconds to seconds
As the leap seconds are ignored, this step is straightforward. Just divide the number of milliseconds by 1000, then round the result down to the nearest integer.
const unixTimestamp = Math.floor(jsTimestamp / 1000);
The final code
const unixTimestamp = Math.floor(Date.now() / 1000); const unixTimestamp = Math.floor(new Date().getTime() / 1000); const unixTimestamp = Math.floor(new Date().valueOf() / 1000);