Home > Web Front-end > JS Tutorial > How Do I Get a Timestamp in JavaScript?

How Do I Get a Timestamp in JavaScript?

Susan Sarandon
Release: 2024-12-12 14:49:17
Original
933 people have browsed it

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:

  • Date.now(): Call this function to retrieve the current timestamp.
  • new Date(): Use the unary operator to cast Date.prototype.valueOf to a number.
  • new Date().valueOf(): Directly call valueOf on a new Date object.

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

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

A slightly faster alternative that may be less readable and potentially break in the future:

Date.now() / 1000 | 0
Copy after login

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

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!

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