Home >Web Front-end >JS Tutorial >How Do I Get a Timestamp in JavaScript?
Obtaining a Timestamp in JavaScript
The need for a single numerical representation of the current date and time, such as a Unix timestamp, often arises in programming tasks. JavaScript offers multiple ways to retrieve timestamps:
Timestamp in Milliseconds:
The number of milliseconds elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC) can be obtained using:
For compatibility with Internet Explorer 8 and earlier, consider creating a shim for Date.now:
if (!Date.now) { Date.now = function () { return new Date().getTime(); } }
You can also call getTime directly: new Date().getTime().
Timestamp in Seconds:
To obtain the number of seconds since the Unix epoch (i.e., a Unix timestamp):
Math.floor(Date.now() / 1000)
A slightly faster alternative that may be less readable and potentially break in the future:
Date.now() / 1000 | 0
Timestamp in Milliseconds (Higher Resolution):
Leverage the performance API, specifically performance.now, to achieve a higher-resolution timestamp:
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() );
The above is the detailed content of How Do I Get a Timestamp in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!