Useful JS Tips

#49 - Easiest way to extract unix timestamp in JS

2016-02-26 by @nmrony

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

<<返回目录