When you create a new Date
instance using the constructor, JavaScript will return date and time represented in human-readable format:
const date = new Date("01/20/2021");
console.log(date); // Wed Jan 20 2021 00:00:00
The Date
object instance already contains the Number
value that represents milliseconds since 1 January 1970 UTC. When you need the UNIX timestamp representation of the date, you can call the valueOf()
method on the Date
instance.
Here’s an example:
const date = new Date("01/20/2021");
console.log(date.valueOf()); // 1611075600000
Or if you want the representation of the current time, you can use the Date.now()
method as follows:
const date = Date.now();
console.log(date); // 1620483960166
The UNIX timestamp above are expressed in milliseconds, you if you want it to be expressed in seconds, you need to divide the value by one thousand. Also, wrap the operation with the Math.floor()
method so that the value returned will round down to the last second.
const date = new Date("01/20/2021").valueOf();
const seconds = Math.floor(date / 1000);
console.log(seconds); // 1611075600
Finally, you can also write the shortest syntax to get the current timestamp by using the unary operator +
before the Date constructor as follows:
console.log(+new Date()); // return the current UNIX timestamp
console.log(+new Date("01/20/2021")); // 1611075600000
And that’s how you can retrieve the UNIX timestamp using JavaScript 😉