JAVASCRIPT

JavaScript date getTime() method: Syntax, Usage, and Examples

The getTime() method in JavaScript returns the number of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC) for a given Date object. This numeric value is extremely useful for date comparisons, time calculations, and storing timestamps. Mastering how to use the JavaScript getTime() method helps developers perform reliable and accurate time-based operations.

How to Use the JavaScript date getTime Method

The getTime() method is available on any instance of the Date object. Its syntax is simple:

dateObject.getTime()
  • Returns an integer representing milliseconds since the Epoch.
  • It does not modify the original Date object.

Basic Example

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

console.log(timestamp); // e.g., 1712748357782

This gives you a timestamp that’s ideal for storing or comparing dates.

When to Use date getTime JavaScript

Comparing Two Dates

You can compare two date objects by subtracting their timestamps:

const start = new Date("2024-01-01");
const end = new Date("2025-01-01");

const difference = end.getTime() - start.getTime();
console.log(difference); // Milliseconds between the two dates

This is perfect for calculating durations.

Storing Timestamps

Use getTime() to store precise timestamps in logs, databases, or session data:

const createdAt = new Date().getTime();
// Store `createdAt` in your database

Timestamps are useful because they’re time zone-independent and easy to compare.

Measuring Elapsed Time

Use the JavaScript date getTime() method to measure how long a block of code takes to run:

const startTime = new Date().getTime();

// Simulate a task
for (let i = 0; i < 1000000; i++) {}

const endTime = new Date().getTime();
console.log("Execution time:", endTime - startTime, "ms");

This gives you a millisecond-precise duration of code execution.

Examples of JavaScript date getTime() in Action

Get the Current Timestamp

const timestamp = new Date().getTime();
console.log(timestamp);

This is equivalent to Date.now() but explicitly uses getTime().

Convert a Timestamp Back to a Date

const timestamp = 1700000000000;
const date = new Date(timestamp);

console.log(date.toString());

You can store timestamps and convert them back into readable date objects later.

Check If a Date Is in the Future

const now = new Date().getTime();
const future = new Date("2030-01-01").getTime();

if (future > now) {
  console.log("This date is in the future.");
}

Simple numeric comparisons are easier and faster than comparing full Date objects.

Countdown Timer Logic

const targetDate = new Date("2025-12-31").getTime();

const interval = setInterval(() => {
  const now = new Date().getTime();
  const remaining = targetDate - now;

  if (remaining <= 0) {
    clearInterval(interval);
    console.log("Countdown complete!");
  } else {
    console.log("Milliseconds left:", remaining);
  }
}, 1000);

This shows how you can build countdown logic using just getTime().

Learn More About JavaScript date getTime

Equivalent to Date.now()

Date.now() gives you the same result as new Date().getTime():

console.log(Date.now() === new Date().getTime()); // true

However, getTime() can be used on any date object, not just the current one.

Useful in Sorting

You can sort an array of dates easily by comparing timestamps:

const dates = [new Date("2022-01-01"), new Date("2023-01-01"), new Date("2021-01-01")];

dates.sort((a, b) => a.getTime() - b.getTime());

console.log(dates); // Sorted by date

Timestamps allow quick numerical comparisons.

Use in Cookies or Local Storage

You might want to store timestamps to track session start times or expiration:

localStorage.setItem("lastVisit", new Date().getTime());

This ensures you can compare times even after the browser is closed.

Calculating Time Differences

You can convert millisecond differences into minutes, hours, or days:

const created = new Date("2025-01-01").getTime();
const now = new Date().getTime();

const diffMs = now - created;
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

console.log("Days since creation:", diffDays);

Use this logic to create human-readable durations.

Be Mindful of Time Zones

getTime() returns UTC-based milliseconds. If you need to consider time zones, use methods like getUTCFullYear() or libraries like date-fns or moment.

Still, for raw time comparisons and storage, getTime() remains reliable and unaffected by time zone differences.

Can Be Used for Expiration Checks

const tokenIssued = new Date().getTime();
const expiresIn = 60 * 60 * 1000; // 1 hour

const isExpired = new Date().getTime() > tokenIssued + expiresIn;
console.log(isExpired ? "Token expired" : "Token valid");

This makes session or token expiration checks fast and straightforward.

The JavaScript date getTime() method gives you an easy and powerful way to work with precise timestamps. You can use it to measure durations, sort events, calculate time differences, or manage time-based logic.

Whether you're handling countdowns, logs, or performance metrics, understanding how to use date getTime() JavaScript techniques gives you better control over time-related functionality in your code.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH