Skip to content

Instantly share code, notes, and snippets.

@zgracem
Created March 30, 2025 04:25
Show Gist options
  • Save zgracem/f9921382fb5a2f2dc8965057ccc74783 to your computer and use it in GitHub Desktop.
Save zgracem/f9921382fb5a2f2dc8965057ccc74783 to your computer and use it in GitHub Desktop.
Print a human-readable string for the interval between two times
require "time"
class ProseTimeSpan
def initialize(time1, time2 = Time.now)
@begin, @end = [time1, time2].map { Time.parse(it.to_s) }.sort
end
def to_i
@end - @begin
end
def to_h
Time.at(to_i).utc.then do
{
years: it.year - 1970,
months: it.month - 1,
days: it.day - 1,
hours: it.hour,
minutes: it.min,
seconds: it.sec
}
end
end
def to_s
to_h.filter_map do |units, qty|
unless qty == 0
unit = units.to_s
unit.delete_suffix!("s") if qty == 1
"#{qty} #{unit}"
end
end.join(", ")
end
include Comparable
def <=>(other)
to_i <=> other.to_i
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment