getTime()

ES1+

Returns the number of milliseconds between the Date object and January 1, 1970 00:00:00 UTC. It exposes the single internal number a Date actually stores, making it the canonical way to convert a Date into a comparable, serializable primitive. For an invalid Date it returns NaN rather than throwing.

Syntax

date.getTime()

Return Value

number

A number representing the milliseconds since UNIX epoch

Examples

JavaScript
const date = new Date('2024-01-15');
console.log(date.getTime());
Output:
// 1705276800000

📌 When to Use

Use getTime() whenever a Date object needs to become a plain number: comparing two dates for equality or order, computing durations by subtraction, storing timestamps in databases or localStorage, deduplicating events, or building sort keys. Two Date objects are never equal under === because object identity is compared, so date1.getTime() === date2.getTime() is the idiomatic equality test. Subtracting getTime() values yields an exact elapsed-milliseconds figure that is immune to time zones and daylight saving, because both values are UTC-based offsets; that makes it the safest basis for "how long between these two instants" logic such as session length, SLA timers, or age-in-days calculations (divide by 86,400,000 with care around DST if you started from local calendar days). It is also the cleanest way to clone a Date: new Date(original.getTime()) produces an independent copy, so later mutating setters cannot corrupt the original. Reach for getTime() at storage and comparison boundaries, and keep Date objects only for the calendar arithmetic and formatting steps where their getters genuinely help. If you need the current time rather than a specific Date object's time, call Date.now() directly and skip the object entirely.

⚠️ Common Mistakes

Comparing Date objects with === or ==. Objects compare by reference, so two Dates representing the same instant are never strictly equal. Relational operators (<, >) happen to work because they coerce via valueOf(), which quietly calls the same internal number, but equality does not coerce, a trap that passes code review easily.

Forgetting that an invalid Date yields NaN. new Date("oops").getTime() returns NaN silently, and every comparison against NaN is false, so records with bad dates neither sort first nor last, they just behave inconsistently. Validate with Number.isNaN(d.getTime()) before trusting the value.

Computing "days between" by dividing a getTime() difference by 86,400,000 when the inputs were local calendar dates. A DST transition makes one local day 23 or 25 hours long, so the division yields 0.958 or 1.042 and Math.floor() then loses or gains a day. Round instead, or do the math in UTC.

Calling getTime() repeatedly inside a sort comparator on Date fields. The values do not change between calls, so re-extracting them O(n log n) times wastes work; extract once into a numeric key first.

Assuming getTime() reflects local time. The value is always the UTC-based epoch offset; the same Date object returns the same getTime() everywhere on Earth. Local rendering differences come from formatting methods, not from this number.

✅ Best Practices

Use timestamp equality for date comparison: a.getTime() === b.getTime(). For ordering, subtracting Dates directly (a - b) works via valueOf() coercion and is a widely understood comparator idiom: dates.sort((a, b) => a - b).

Persist dates as epoch milliseconds (or ISO 8601 strings) rather than locale-formatted text. Numeric timestamps index efficiently, compare with plain operators, and survive locale, timezone, and ICU changes unscathed.

Clone before mutating: const copy = new Date(original.getTime()). JavaScript Date setters mutate in place, and sharing one Date instance across functions is a common source of spooky action at a distance.

Guard invalid dates at the boundary with Number.isNaN(date.getTime()); it is the cheapest complete validity check for a Date object and avoids the RangeError that toISOString() would throw later.

For duration math that must respect calendars (months, DST-aware days), prefer the Temporal API (Temporal.Instant for exact time, Temporal.PlainDate.since for calendar differences) or a library like date-fns; raw millisecond arithmetic is exact for instants but wrong for calendar units.

⚡ Performance Notes

getTime() simply reads the internal time value a Date already stores, so it is effectively free, comparable to a property read, and engines inline it aggressively. The performance considerations are all around it, not in it: creating Date objects just to call getTime() allocates garbage, so prefer Date.now() for the current time, and when sorting or filtering large arrays by date, materialize the numeric keys once instead of calling new Date(str).getTime() inside the comparator, which multiplies parsing cost by O(n log n). Comparing raw numbers with < and > is faster than any Date-object comparison path because it avoids valueOf() dispatch. For bulk analytics over tens of thousands of rows, converting a date column to a numeric array (or a typed array) first turns date logic into pure arithmetic the JIT optimizes well.

🌍 Real World Example

Event Scheduler with Date Comparison

Event dashboards constantly need the same three views: everything sorted chronologically, upcoming items, and past items. This example converts each event date to its timestamp once and then relies on plain numeric comparison for sorting, filtering, and finding the next event. Doing the comparisons on numbers rather than Date objects keeps the logic trivially correct (no reference-equality traps) and fast even with large event lists. The identical pattern applies to message timelines, order histories, and content scheduling queues.

function organizeEvents(events) {
  const now = Date.now();

  const sortedEvents = [...events].sort(
    (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
  );

  return {
    upcoming: sortedEvents.filter(e => new Date(e.date).getTime() > now),
    past: sortedEvents.filter(e => new Date(e.date).getTime() <= now),
    nextEvent: sortedEvents.find(e => new Date(e.date).getTime() > now)
  };
}

const events = [
  { name: 'Meeting', date: '2024-12-01' },
  { name: 'Conference', date: '2024-06-15' },
  { name: 'Workshop', date: '2024-03-20' }
];

console.log(organizeEvents(events));

Related Methods