JavaScript Date getTime() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Epoch milliseconds

What You’ll Learn

getTime() returns the number of milliseconds since the Unix epoch (Jan 1, 1970 UTC) for a Date instant. This guide covers syntax, duration math, timestamp round-trips, comparisons, and how it differs from getMilliseconds().

01

Syntax

date.getTime()

02

Epoch ms

Large integer

03

Duration

Subtract timestamps

04

Round-trip

new Date(ms)

05

vs now

Date.now()

06

Invalid

Returns NaN

Introduction

APIs, databases, and sort functions often store time as a single number. The getTime() method exposes that number from any Date object—milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Use it for elapsed duration, ordering events, and serializing instants. For the current timestamp without building a Date, see Date.now().

Understanding the getTime() Method

Date.prototype.getTime() is a zero-argument instance method. It never mutates the original Date—it returns the stored instant as a numeric timestamp.

The same instant always yields the same getTime() value regardless of local timezone. That makes it ideal for comparison and arithmetic; local getters like getHours() are for display, not for measuring duration.

💡
Beginner Tip

Subtracting two Date objects (end - start) works because JavaScript coerces them to numbers via getTime().

📝 Syntax

JavaScript
dateObj.getTime()

Parameters

  • None.

Return value

  • Number of milliseconds since the Unix epoch for a valid Date.
  • NaN if dateObj is an invalid Date.

⚡ Quick Reference

GoalCode
Current timestampnew Date().getTime() or Date.now()
Elapsed millisecondsend.getTime() - start.getTime()
Date from timestampnew Date(1721203200000)
Which is earlier?a.getTime() < b.getTime()
Invalid date checkNumber.isNaN(date.getTime())
Same instant?a.getTime() === b.getTime()

📋 getTime() vs Similar APIs

These APIs all involve milliseconds but serve different jobs. Pick the one that matches your task.

getTime()
epoch ms

Instance method

Date.now()
now ms

Static shortcut

valueOf()
same ms

Coercion hook

getMilliseconds()
0–999

Sub-second only

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Sample timestamps will differ on your machine when reading “now.”

📚 Getting Started

Read the epoch milliseconds from the current time.

Example 1 — Get the Current Timestamp

Call getTime() on a new Date() to read milliseconds since the epoch.

JavaScript
const now = new Date();
const timestamp = now.getTime();

console.log("Timestamp (ms):", timestamp);
Try It Yourself

How It Works

The value is a large integer that grows every millisecond. It identifies an instant globally—not a local clock component.

📈 Practical Patterns

Duration, reconstruction, comparison, and benchmarking.

Example 2 — Calculate the Difference Between Two Dates

Subtract timestamps to get elapsed milliseconds between two instants.

JavaScript
const start = new Date(2026, 0, 1);
const end = new Date(2026, 1, 1);

const diffMs = end.getTime() - start.getTime();
const diffDays = diffMs / (1000 * 60 * 60 * 24);

console.log("Difference (ms):", diffMs);
console.log("Difference (days):", diffDays);
Try It Yourself

How It Works

Jan 1 to Feb 1, 2026 spans 31 days in this example. Divide by 86400000 (ms per day) when you need day counts.

Example 3 — Rebuild a Date from a Timestamp

Pass epoch milliseconds to the Date constructor.

JavaScript
const timestamp = 1721203200000;
const restored = new Date(timestamp);

console.log(restored.toISOString());
// 2024-07-17T08:00:00.000Z
Try It Yourself

How It Works

getTime() and new Date(ms) are inverse operations for the same instant. JSON APIs often store timestamps this way.

Example 4 — Compare Which Date Is Earlier

Sort or compare events using numeric timestamps.

JavaScript
const meetingA = new Date(2026, 6, 4, 10, 0);
const meetingB = new Date(2026, 6, 4, 14, 30);

if (meetingA.getTime() < meetingB.getTime()) {
  console.log("Meeting A is earlier.");
} else {
  console.log("Meeting B is earlier or same.");
}
Try It Yourself

How It Works

Comparing numbers is simpler than comparing year/month/day fields separately. Arrays of dates sort cleanly with (a, b) => a.getTime() - b.getTime().

Example 5 — Measure Elapsed Time for a Task

Snapshot start and end timestamps around work you want to benchmark.

JavaScript
const start = Date.now();

let sum = 0;
for (let i = 0; i < 200000; i++) {
  sum += i;
}

const elapsed = Date.now() - start;
console.log("Elapsed:", elapsed, "ms");
Try It Yourself

How It Works

Date.now() is equivalent to new Date().getTime() but skips allocating a Date object. Both return epoch milliseconds suitable for duration math.

🚀 Common Use Cases

  • API payloads — store createdAt as epoch ms.
  • Sorting events — order by getTime().
  • Cooldown timers — compare now vs last action timestamp.
  • Session expiryDate.now() > expiresAt.
  • Benchmarks — measure code block duration.
  • Cache keys — bust caches with timestamp suffixes.

🧠 How getTime() Represents an Instant

1

Date object

Internally holds one instant as UTC milliseconds.

Storage
2

getTime()

Returns that number directly—no timezone conversion.

Read
3

Math

Subtract, compare, or serialize the timestamp.

Use
4

Rebuild

new Date(ms) recreates the same instant.

📝 Notes

  • getTime() equals valueOf() on valid dates.
  • Invalid dates return NaN—use that for validation.
  • Not the same as getMilliseconds() (0–999 sub-second).
  • Prefer Date.now() when you only need the current ms once.
  • Divide carefully when converting ms to days (watch DST if using local midnight tricks).
  • For high-precision benchmarks in browsers, consider performance.now() (relative, not epoch).

Browser & Runtime Support

Date.prototype.getTime() has been available since the first JavaScript Date implementation (ES1). It works in every browser and Node.js.

Baseline · ES1

Date.prototype.getTime()

Supported in Chrome, Firefox, Safari, Edge, Internet Explorer, and all Node.js versions. No polyfill required.

99% Universal API
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Date.getTime() Excellent

Bottom line: Safe everywhere. Store epoch ms for APIs; format to local strings only at the UI boundary.

Conclusion

getTime() is the standard way to read a Date as epoch milliseconds. Use it for duration, comparison, and serialization; use Date.now() for a quick “now” snapshot.

Next, learn Date.now() as the static shortcut, or toISOString() for UTC string export.

💡 Best Practices

✅ Do

  • Use getTime() for comparisons and duration
  • Validate with Number.isNaN(date.getTime())
  • Store timestamps in APIs and databases
  • Use Date.now() for simple “now” reads
  • Rebuild with new Date(ms) when parsing stored values

❌ Don’t

  • Confuse getTime() with getMilliseconds()
  • Compare local date parts when getTime() suffices
  • Assume ISO strings parse the same in every timezone
  • Feature-detect getTime() in modern apps
  • Display raw epoch ms to end users without formatting

Key Takeaways

Knowledge Unlocked

Five things to remember about Date.getTime()

Your foundation for timestamps in JavaScript.

5
Core concepts
🔢 02

Epoch ms

Since 1970.

Format
🔄 03

Subtract

Duration.

Math
🛠 04

Rebuild

new Date(ms)

Round-trip
05

Not getMs

0–999 vs epoch.

Pitfall

❓ Frequently Asked Questions

The number of milliseconds since January 1, 1970 00:00:00 UTC (the Unix epoch) for that Date instant. It is a large integer, not a 0–59 clock component.
getTime() is called on a Date instance. Date.now() is a static method that returns the current epoch milliseconds without creating a Date object. For 'now', they match: new Date().getTime() === Date.now().
getTime() returns full epoch milliseconds (e.g. 1721203200000). getMilliseconds() returns only 0–999 for the sub-second fraction within the current second.
NaN. That is the standard way to detect invalid dates: Number.isNaN(date.getTime()).
No. Two Date objects representing the same instant return the same getTime() value everywhere. Local getters like getHours() can differ; getTime() identifies the instant.
Subtract their timestamps: later.getTime() - earlier.getTime(). The result is elapsed milliseconds. Divide by 1000 for seconds, 60000 for minutes, etc.
Did you know?

When you write end - start with two Date objects, JavaScript calls valueOf(), which returns the same number as getTime(). That is why date subtraction gives elapsed milliseconds.

Continue to Date.now()

Learn the static shortcut for reading the current epoch milliseconds without creating a Date object.

Date.now() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful