How do I get a timestamp in JavaScript?

Timestamp in milliseconds

To get the number of milliseconds since Unix epoch, call Date.now:

Date.now()

Alternatively, use the unary operator + to call Date.prototype.valueOf:

+ new Date()

Alternatively, call valueOf directly:

new Date().valueOf()

To support IE8 and earlier (see compatibility table), create a shim for Date.now:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

Alternatively, call getTime directly:

new Date().getTime()

Timestamp in seconds

To get the number of seconds since Unix epoch, i.e. Unix timestamp:

Math.floor(Date.now() / 1000)

Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):

Date.now() / 1000 | 0

Timestamp in milliseconds (higher resolution)

Use performance.now:

var isPerformanceSupported = (
    window.performance &&
    window.performance.now &&
    window.performance.timing &&
    window.performance.timing.navigationStart
);

var timeStampInMs = (
    isPerformanceSupported ?
    window.performance.now() +
    window.performance.timing.navigationStart :
    Date.now()
);

console.log(timeStampInMs, Date.now());

Leave a Comment