Home > Web Front-end > JS Tutorial > How Do I Get a Unix Timestamp (or Milliseconds Since Epoch) in JavaScript?

How Do I Get a Unix Timestamp (or Milliseconds Since Epoch) in JavaScript?

Susan Sarandon
Release: 2024-12-10 22:05:12
Original
339 people have browsed it

How Do I Get a Unix Timestamp (or Milliseconds Since Epoch) in JavaScript?

How to Obtain Timestamp in JavaScript

To obtain a representation of the current date and time as a single numerical value, similar to a Unix timestamp, JavaScript provides several methods.

Timestamp in Milliseconds:

To retrieve the number of milliseconds since the Unix epoch, use Date.now():

Date.now();
Copy after login

Alternatively, for compatibility with older browsers, you can use the following:

+new Date();
Copy after login

Timestamp in Seconds (Unix Timestamp):

To obtain the number of seconds since the Unix epoch, commonly known as the Unix timestamp, calculate the quotient of Date.now() divided by 1000:

Math.floor(Date.now() / 1000);
Copy after login

Higher Resolution Timestamp in Milliseconds:

For a higher resolution timestamp in milliseconds, 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()
);
Copy after login

The above is the detailed content of How Do I Get a Unix Timestamp (or Milliseconds Since Epoch) 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