# How to get the current timestamp in JavaScript

> Learn how to get the current UNIX timestamp in JavaScript with Date.now(), and how to convert it from milliseconds to seconds using Math.floor().

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2018-05-18 | Updated: 2019-06-03 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-get-timestamp-javascript/

The UNIX timestamp is an integer that represents **the number of seconds elapsed since January 1 1970**.

On UNIX-like machines, which include Linux and macOS, you can type `date +%s` in the terminal and get the UNIX timestamp back:

```bash
$ date +%s
1524379940
```

If you have a timestamp and want to know which date it corresponds to (or the reverse), I built a free [timestamp converter](https://flaviocopes.com/tools/timestamp-converter/) that handles timezones too.

The current timestamp can be fetched by calling the `now()` method on the `Date` object:

```js
Date.now()
```

You could get the same value by calling

```js
new Date().getTime()

or

new Date().valueOf()
```

> Note: IE8 and below do not have the `now()` method on `Date`. Look for a polyfill if you need to support IE8 and below, or use `new Date().getTime()` if `Date.now` is undefined (as that's what a polyfill would do)

The timestamp in [JavaScript](https://flaviocopes.com/javascript/) is expressed in **milliseconds**.

To get the timestamp expressed in seconds, convert it using:

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

> Note: some tutorials use `Math.round()`, but that will approximate to the next second even if the second is not fully completed.

or, less readable:

```js
~~(Date.now() / 1000)
```

I've seen tutorials using

```js
+new Date
```

which might seem a weird statement, but it's perfectly correct JavaScript code. The _unary operator +_ automatically calls the `valueOf()` method on any object it is assigned to, which returns the timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object that's immediately discarded.

To generate a date from a timestamp, use `new Date(<timestamp>)` but make sure you pass a number (a string will get you an "invalid date" result - use `parseInt()` in doubt)
