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

How Do I Get a Timestamp in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 14:49:17928browse

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

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!

Statement:
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