The Unix timestamp is an integer value that represents the number of seconds elapsed since the Unix Epoch on January 1st, 1970, at 00:00:00 UTC. In short, a Unix timestamp is the number of seconds between a specific date and the Unix Epoch.

The JavaScript Date object provides several methods to manipulate date and time. You can get the current timestamp by calling the now() function on the Date object like below:

const timestamp = Date.now()

This method returns the current UTC timestamp in milliseconds. The Date.now() function works in almost all modern browsers except IE8 and earlier versions. But you can fix this by writing a small polyfill:

if(!Date.now) {
    Date.now = () => new Date().getTime()
}

Otherwise, you can get the same timestamp by calling other JavaScript functions that work in older browsers too:

const timestamp = new Date().getTime()
// OR
const timestamp = new Date().valueOf()

To convert the timestamp to seconds (Unix time), you can do the following:

const unixTime = Math.floor(Date.now() / 1000)

The unixTime variable now contains the Unix timestamp for the current date and time, depending on the user's web browser.

It is recommended to use Date.now() whenever possible, even with polyfill. Unlike the getTime() method, it is shorter and doesn't create a new instance of the Date object.

If you are using a Unix-compatible machine like Ubuntu or macOS, you can also get the current Unix timestamp by typing the following command in your terminal:

$ date +%s
1567562058

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.