# How to get the Unix timestamp in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 4, 2019, updated Sep 11, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/unix-timestamp-javacript

> Learn about different ways to generate the current Unix timestamp in JavaScript.

The [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time) 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:

```javascript
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:

```javascript
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:

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

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

```javascript
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:

```bash
$ date +%s
1567562058
```
