snippetjavascriptCritical
How do I get a timestamp in JavaScript?
Viewed 0 times
timestamphowjavascriptget
Problem
I want a single number that represents the current date and time, like a Unix timestamp.
Solution
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call
Alternatively, use the unary operator
Alternatively, call
To support IE8 and earlier (see compatibility table), create a shim for
Alternatively, call
Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Timestamp in milliseconds (higher resolution)
Use
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 | 0Timestamp 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());Code Snippets
+ new Date()new Date().valueOf()if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}new Date().getTime()Math.floor(Date.now() / 1000)Context
Stack Overflow Q#221294, score: 6182
Revisions (0)
No revisions yet.