The UNIX timestamp is an integer value that represents the number of seconds elapsed since Unix Epoch on January 1st, 1970 at 00:00:00 UTC. In short, it is a way to track the time as a running total of seconds. Hence, a UNIX timestamp is simply the number of seconds between a specific date and the UNIX Epoch.

The JavaScript Date object provides a number of methods for working with dates and times. 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. Date.now() works in almost all modern browsers except IE8 and earlier versions. But you can easily 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 other functions like getTime(), It is shorter and doesn't create a new instance of Date object.

Using Terminal

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

$ date +%s
1567562058

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.