Easiest way to extract unix timestamp in JS
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
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOWA short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW