JavaScript getTime()

getTime() returns the timestamp stored by a JavaScript Date: milliseconds since 1 January 1970 00:00:00 UTC. Dates before the epoch return negative values.

const date = new Date();
const milliseconds = date.getTime();
console.log(milliseconds);

Timestamps are useful for comparing dates, measuring elapsed time, copying Date objects, and storing an instant independently of display format.

getTime() Syntax Top ↑

const timestamp = date.getTime();

Unix Epoch and Negative Timestamps Top ↑

const epoch = new Date(0);
const beforeEpoch = new Date(-1000);

Compare and Sort Dates Top ↑

const a = new Date("2026-09-10T10:00:00Z");
const b = new Date("2026-09-11T10:00:00Z");
console.log(a.getTime() < b.getTime());
const dates = [b, a];
dates.sort((x, y) => x.getTime() - y.getTime());

Calculate Elapsed Time Top ↑

const start = new Date("2026-09-10T10:00:00Z");
const end = new Date("2026-09-10T10:02:30Z");
const seconds = (end.getTime() - start.getTime()) / 1000;
console.log(seconds); // 150

The original tutorial also uses timestamps to calculate process duration; see the process-time demo.

Copy a Date Object Top ↑

const original = new Date();
const copy = new Date(original.getTime());

getTime() vs Date.now() Top ↑

const fromObject = (new Date()).getTime();
const directly = Date.now();

Use Date.now() when you only need the current timestamp and do not need a Date object.

Invalid Dates and NaN Top ↑

const bad = new Date("invalid");
console.log(bad.getTime()); // NaN

Use the Right API for Performance Timing Top ↑

Date.now() and getTime() represent wall-clock time. For measuring short code execution intervals in a browser, performance.now() provides a monotonic, higher-resolution timer.

const start = performance.now();
// work to measure
const elapsed = performance.now() - start;

Common getTime() Mistakes Top ↑

  • Assuming the number is seconds instead of milliseconds.
  • Using wall-clock time for precise performance benchmarking.
  • Failing to detect NaN for invalid dates.
  • Comparing Date objects by identity instead of comparing timestamps.

getMonth() Date Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer