How to diff two datetimes
This post's featured URL for sharing metadata is https://www.jvt.me/img/profile.jpg.
Today I've been looking at how to calculate the number of seconds/minutes/hours between two datetimes.
As this is both for me, and for other humans to read, I wanted to provide both the raw number, and a Xhours Yminutes
view, too.
I couldn't find an online calculator that would allow me to use an ISO8601 datetime, so spent ~10 minutes doing it myself.
I started with Ruby, but it failed me being able to work this out easily, due to this gotcha, so then I found this Javascript example, which I've modified:
var before = new Date(process.argv[2])
var after = new Date(process.argv[3])
if (process.argv[2] >= process.argv[3]) {
// swap
const tmp = before
before = after
after = tmp
}
// https://stackoverflow.com/questions/18023857/compare-2-iso-8601-timestamps-and-output-seconds-minutes-difference
const diffMs = after - before
const minutes = diffMs / 1000 / 60
console.log(`Human-y: ${Math.floor(minutes / 60 * 1)}h ${(minutes) % 60}m`)
console.log(`Seconds: ${diffMs / 1000}`)
console.log(`Minutes: ${minutes}`)
console.log(`Hours: ${minutes / 60 * 1.0}`)
From here, I can run:
% node between.js 2024-10-10T13:12Z 2024-10-31T19:45:00.000Z
Human-y: 510h 33m
Seconds: 1837980
Minutes: 30633
Hours: 510.55