Retrieving Timestamps in JavaScript
Timestamping plays a crucial role in web development for tasks such as tracking events, managing state, and ensuring data integrity. In JavaScript, there are several methods to obtain a timestamp, representing the current date and time as a numerical value.
Timestamp in milliseconds
To retrieve the number of milliseconds since the Unix epoch (00:00:00 UTC on January 1, 1970), use the Date.now() method:
Date.now()
Alternatively, you can use the unary operator to call Date.prototype.valueOf or call valueOf directly:
+ new Date() new Date().valueOf()
Timestamp in seconds (Unix timestamp)
To obtain the Unix timestamp, which represents the number of seconds since the Unix epoch, use the following formula:
Math.floor(Date.now() / 1000)
Timestamp in milliseconds (higher resolution)
For higher precision, considering fractional milliseconds, the following approach using performance.now may be employed:
var timeStampInMs = ( isPerformanceSupported ? window.performance.now() + window.performance.timing.navigationStart : Date.now() ); console.log(timeStampInMs, Date.now());
The above is the detailed content of How Can I Get Timestamps in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!