Skip to content

Commit

Permalink
patch: Converting miliseconds to Second as Unix timestamp is calculat…
Browse files Browse the repository at this point in the history
…ed on seconds
  • Loading branch information
nurrony committed Feb 27, 2016
1 parent d80b458 commit 1ee94e9
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions _posts/en/2016-02-26-extract-unix-timestamp-easily.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,38 @@ categories:
We frequently need to calculate with unix timestamp. There are several ways to grab the timestamp. For current unix timestamp easiest and fastest way is

```js
const timestamp = Date.now();
const dateTime = Date.now();
const timestamp = ~~(dateTime / 1000);
```
or

```js
const timestamp = new Date().getTime();
const dateTime = new Date().getTime();
const timestamp = ~~(dateTime / 1000);
```

To get unix timestamp of a specific date pass `yyyy-mm-dd` as a parameter of `Date` constructor. For example

```js
const timestamp = new Date('2012-06-08').getTime()
const dateTime = new Date('2012-06-08').getTime();
const timestamp = ~~(dateTime / 1000);
```
You can just add a `+` sign also when declaring a `Date` object like below

```js
const timestamp = +new Date()
const dateTime = +new Date();
const timestamp = ~~(dateTime / 1000);
```
or for specific date

```js
const timestamp = +new Date('2012-06-08')
const dateTime = +new Date('2012-06-08');
const timestamp = ~~(dateTime / 1000);
```
Under the hood the runtime calls `valueOf` method of the `Date` object. Then the unary `+` operator calls `toNumber()` with that returned value. For detailed explanation please check the following links

* [Date.prototype.valueOf](http://es5.github.io/#x15.9.5.8)
* [Unary + operator](http://es5.github.io/#x11.4.6)
* [toNumber()](http://es5.github.io/#x9.3)
* [toNumber()](http://es5.github.io/#x9.3)
* [Date Javascript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)

0 comments on commit 1ee94e9

Please sign in to comment.