How to diff two datetimes

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

Written by Jamie Tanna's profile image Jamie Tanna on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation.

This blog post is 100% human-written, and has nothing derived from LLMs (be it code, editorial support or prose).

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.