Get time difference between datetimes
Here's how to calculate the time difference in JavaScript using basic Date objects:
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:
For durations beyond 24 hours, let moment.duration()
take the wheel:
To polish duration appearance, the moment-duration-format
plugin does a splendid job:
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:
Looking for a human-readable format? There is moment.humanize()
for you:
When durations demand custom formatting
Some folks prefer their own ways, for them there's custom duration formatting:
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!
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!
Was this article helpful?