Get the Current Timestamp in JavaScript

Apr 28, 2019

A Unix timestamp is a number representing the number of seconds since January 1, 1970. Unix timestamps are a common method for representing points in time because they only require 64 bits (or 32 bits until 2038), can be compared using basic math operators like > and <=, and are timezone-independent.

JavaScript's Date.now() function returns the number of milliseconds since January 1, 1970. In other words, Date.now() doesn't give you the Unix timestamp, but you can easily convert by dividing by 1000:

// 1556372741848, _milliseconds_ since Jan 1 1970
Date.now();

// 1556372741, _seconds_ since Jan 1, 1970. This is the Unix timestamp
Math.floor(Date.now() / 1000);

Given an existing date, you can use either the getTime() function or the valueOf() function to get the number of milliseconds since January 1, 1970. These two functions are equivalent.

const d = new Date('2019-06-01');

// Both get you the number of milliseconds since the Unix epoch
d.getTime(); // 1559347200000
d.valueOf(); // 1559347200000

The reason why getTime() and valueOf() are separate functions is that JavaScript uses valueOf() functions for implicit type conversions.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials