Explain Codes LogoExplain Codes Logo

Get time difference between datetimes

javascript
moment-js
date-time
timezones
Alex KataevbyAlex Kataev·Feb 8, 2025
TLDR

Here's how to calculate the time difference in JavaScript using basic Date objects:

const start = new Date('2023-01-01T00:00:00'); const end = new Date('2023-01-01T02:30:00'); const diffHrs = (end - start) / 3.6e6; // Pays off to remember your scientific notation, eh? console.log(diffHrs); // Outputs: 2.5, time flies!

You can swap / 3.6e6 with / 60000 for minutes, and / 1000 for seconds.

Dates are complex, moment.js can help

Working with timezones and daylight saving time can get messy, but moment.js shines here. It nimbly adjusts for these:

const moment = require('moment'); // Who would've thought moments are imported! const start = moment('2023-03-10T03:00:00Z'); const end = moment('2023-03-11T04:00:00Z'); const diff = end.diff(start); // Time warp in milliseconds console.log(moment.utc(diff).format('HH:mm:ss')); // Brings back the good old formatted time

For durations beyond 24 hours, let moment.duration() take the wheel:

const duration = moment.duration(diff); // Like an aged wine, longer durations need special handling console.log(`${duration.days()} days ${duration.hours()} hours ${duration.minutes()} minutes`); // Now, humanized!

To polish duration appearance, the moment-duration-format plugin does a splendid job:

moment.duration(diff).format("d[d] h[h] m[m] s[s]"); // Now, that's classy!

But remember guys, with great durations, come great responsibilities.

Breaking down long durations

Long durations are like a grand buffet, they're often better when broken down into palatable portions:

const diffInMs = end - start; // Difference in milliseconds, as raw as it gets const diffDays = Math.floor(diffInMs / 86400000); // All-day-all-night calculation const diffHrs = Math.floor((diffInMs % 86400000) / 3600000); // Calculates the chilling hours after a day's work const diffMins = Math.round(((diffInMs % 86400000) % 3600000) / 60000); // Seconds to minutes: the final showdown console.log(`Days: ${diffDays}, Hours: ${diffHrs}, Minutes: ${diffMins}`); // It's showtime!

Looking for a human-readable format? There is moment.humanize() for you:

console.log(moment.duration(now.diff(then)).humanize()); // Because we're all human, after all

When durations demand custom formatting

Some folks prefer their own ways, for them there's custom duration formatting:

const diff = moment.duration(now.diff(then)); const formatted = [ parseInt(diff.asHours()), diff.minutes(), diff.seconds() ].join(':').padStart(2, '0'); // Because sometimes, zeros do matter! console.log(formatted); // And...voila!

And remember, our time-warping test subject here may trip over timezones and daylight saving shifts.

Handling bad date behaviours

Bad datetime formats are like bad pizzas, disgusting! Ensure the date values are in expected format. Validate, or else, prepare for a date disaster!

if (!moment(start).isValid() || !moment(end).isValid()) { // Oh oh! Someone's got a bad date! }

For durations beyond 24 hours, standard tricks may not impress, you might need a custom formatter.

A few more things to remember

Milliseconds are the underdogs, always convert duration to milliseconds for accurate results with moment.js. But remember to convert back to meaningful formats later. A millisecond is somewhat a tad too short to make an impression!