Course contentsShow
← JavaScript
Lesson 1628 of 2,72335. Standard Library and Built-insFree lesson

Calculating Time Differences with getTime

Compute millisecond differences between dates using getTime or valueOf for precise duration calculations.

Calculating Time Differences with getTime

You'll learn how to compute precise time differences in milliseconds between two dates using the getTime method.

Understanding Time Differences

When you need to know exactly how much time has elapsed between two moments—whether for performance measurement, age calculation, or countdown timers—JavaScript's getTime() method is your go-to tool. This method returns the number of milliseconds since January 1, 1970 (the Unix epoch), giving you a precise numeric value you can use in calculations.

Think of it like measuring distance: if two cities are at mile markers 100 and 250 on a highway, the distance between them is simply 250 - 100 = 150 miles. Similarly, subtracting one date's millisecond value from another gives you the time elapsed.

Using getTime for Calculations

const startDate = new Date('2024-01-01T00:00:00');
const endDate = new Date('2024-01-10T00:00:00');

const diffInMilliseconds = endDate.getTime() - startDate.getTime();
console.log(diffInMilliseconds); // 777600000

// Convert to more useful units
const diffInSeconds = diffInMilliseconds / 1000;
const diffInMinutes = diffInSeconds / 60;
const diffInHours = diffInMinutes / 60;
const diffInDays = diffInHours / 24;

console.log(diffInDays); // 9

The valueOf Alternative

You can also use valueOf(), which works identically to getTime():

const date1 = new Date('2024-03-15');
const date2 = new Date('2024-03-20');

const diff = date2.valueOf() - date1.valueOf();
console.log(diff); // 432000000 milliseconds

Practical Applications

// Calculating age in days
const birthday = new Date('1990-05-15');
const today = new Date();
const ageInDays = Math.floor((today.getTime() - birthday.getTime()) / (1000 * 60 * 60 * 24));
console.log(`You are ${ageInDays} days old`);

Key Takeaway: Use getTime() or valueOf() to convert dates to milliseconds, then subtract them for precise duration calculations that you can convert to any time unit needed.