From 1ee94e990bc2f8383a8924840036a40db5f7a24a Mon Sep 17 00:00:00 2001 From: Nur Rony Date: Sat, 27 Feb 2016 19:12:16 +0600 Subject: [PATCH] patch: Converting miliseconds to Second as Unix timestamp is calculated on seconds --- ...016-02-26-extract-unix-timestamp-easily.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/_posts/en/2016-02-26-extract-unix-timestamp-easily.md b/_posts/en/2016-02-26-extract-unix-timestamp-easily.md index 48a26e45..1b90b5d4 100644 --- a/_posts/en/2016-02-26-extract-unix-timestamp-easily.md +++ b/_posts/en/2016-02-26-extract-unix-timestamp-easily.md @@ -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) \ No newline at end of file +* [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)