getTime()

ES1+

Returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

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() when you need to compare dates, store dates in databases, calculate time differences, or sort dates.

⚠️ Common Mistakes

Comparing Date objects directly with === instead of comparing their getTime() values.

Using getTime() on an invalid Date object returns NaN, not throwing an error.

✅ Best Practices

Use getTime() for date comparisons: date1.getTime() === date2.getTime() for equality checks.

Store timestamps as numbers in databases for efficient indexing and querying.

⚡ Performance Notes

getTime() is a simple property access and extremely fast. Comparing timestamps with < > operators is much faster than creating new Date objects for each comparison.

🌍 Real World Example

Event Scheduler with Date Comparison

Sort and filter events based on their timestamps, identifying upcoming and past events.

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