Converting Milliseconds to Human-Readable Durations
You'll learn how to transform raw millisecond time differences into readable formats like "2 days, 5 hours, 30 minutes, 15 seconds."
When you calculate time differences using getTime(), you get a result in milliseconds—a single large number that's hard for humans to interpret. Converting this into days, hours, minutes, and seconds makes the duration meaningful at a glance.
The Core Technique: Division and Remainders
The strategy is to repeatedly break down the milliseconds into larger time units, working from largest to smallest:
- Days: Divide milliseconds by
86,400,000(24 × 60 × 60 × 1000) - Hours: Get the remainder, divide by
3,600,000(60 × 60 × 1000) - Minutes: Get that remainder, divide by
60,000(60 × 1000) - Seconds: Get that remainder, divide by
1000
Think of it like making change from a large bill: you first count out the biggest denomination (days), then use what's left for the next denomination (hours), and so on.
Example Implementation
const date1 = new Date('2024-01-01T00:00:00');
const date2 = new Date('2024-01-03T14:35:42');
const diffMs = date2.getTime() - date1.getTime();
const days = Math.floor(diffMs / 86400000);
const hours = Math.floor((diffMs % 86400000) / 3600000);
const minutes = Math.floor((diffMs % 3600000) / 60000);
const seconds = Math.floor((diffMs % 60000) / 1000);
console.log(`${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds`);
// "2 days, 14 hours, 35 minutes, 42 seconds"
The modulo operator (%) gives you the "leftover" milliseconds after extracting each larger unit, ensuring each component represents only its portion of the total duration.
Key Takeaway: Convert milliseconds to human-readable durations by using division to extract days, hours, minutes, and seconds, with the remainder operator ensuring each unit only represents its slice of the total time.