How to get the current timestamp in JavaScript

Find out how JavaScript provides you to generate the current UNIX timestamp


The UNIX timestamp is an integer, which meansthe number of seconds elapsed since January 1 1970.

On UNIX-like computers including Linux and macOS, you can typedate +%sIn the terminal, and get the UNIX timestamp:

$ date +%s
1524379940

You can get the current timestamp by calling the following commandnow()On the methodDatepurpose:

Date.now()

You can get the same value by calling

new Date().getTime()

or

new Date().valueOf()

Note: Not available in IE8 and belownow()Method openDate. If you need to support IE8 and below, please look for a polyfillnew Date().getTime()in caseDate.nowIs undefined (because that is what the polyfill does)

The timestamp in JavaScript is represented asmillisecond.

To get the timestamp in seconds, use the following command to convert:

Math.floor(Date.now() / 1000)

Note: some tutorials useMath.round(), But even if the second is not fully completed, it will be close to the next second.

Or, less readable:

~~(Date.now() / 1000)

I have seen the tutorial

+new Date

This may seem weird, but this is completely correct JavaScript code. ThisUnary operator+Automatic callvalueOf()A method assigned to any object that returns a timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object, which is immediately discarded.

To generate a date from a timestamp, usenew Date(<timestamp>)But make sure you pass a number (the string will give you the "invalid date" result-useparseInt()doubt)

Download mine for freeJavaScript beginner's manual


More js tutorials: