Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 1.66 KB

2016-02-26-extract-unix-timestamp.md

File metadata and controls

50 lines (37 loc) · 1.66 KB

title: Easiest way to extract unix timestamp in JS tip-number: 49 tip-username: nmrony tip-username-profile: https://github.com/nmrony tip-tldr: In Javascript you can easily get the unix timestamp

  • /en/extract-unix-timestamp-easily/

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

const dateTime = Date.now();
const timestamp = Math.floor(dateTime / 1000);

or

const dateTime = new Date().getTime();
const timestamp = Math.floor(dateTime / 1000);

To get unix timestamp of a specific date pass YYYY-MM-DD or YYYY-MM-DDT00:00:00Z as parameter of Date constructor. For example

const dateTime = new Date('2012-06-08').getTime();
const timestamp = Math.floor(dateTime / 1000);

You can just add a + sign also when declaring a Date object like below

const dateTime = +new Date();
const timestamp = Math.floor(dateTime / 1000);

or for specific date

const dateTime = +new Date('2012-06-08');
const timestamp = Math.floor(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