Home > Web Front-end > JS Tutorial > How Can I Get Timestamps in JavaScript?

How Can I Get Timestamps in JavaScript?

Mary-Kate Olsen
Release: 2024-12-09 11:44:12
Original
607 people have browsed it

How Can I Get Timestamps in JavaScript?

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()
Copy after login

Alternatively, you can use the unary operator to call Date.prototype.valueOf or call valueOf directly:

+ new Date()
new Date().valueOf()
Copy after login

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)
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template