Skip to content

Instantly share code, notes, and snippets.

@chuckremes
Created June 13, 2018 20:27
Show Gist options
  • Save chuckremes/9d7dede5843f83744e129d7fe7de2e55 to your computer and use it in GitHub Desktop.
Save chuckremes/9d7dede5843f83744e129d7fe7de2e55 to your computer and use it in GitHub Desktop.
MinuteSeconds = 60
HourSeconds = 60 * MinuteSeconds
DaySeconds = 24 * HourSeconds
MonthSeconds = 30 * DaySeconds
YearSeconds = 12 * MonthSeconds
DecadeSeconds = 10 * YearSeconds
CenturySeconds = 10 * DecadeSeconds
def time_unit(seconds, unit_seconds, unit_name, string)
if seconds >= unit_seconds
units = (seconds / unit_seconds.to_f).to_i
seconds -= (units * unit_seconds)
substring = units > 1 ? (unit_name + 's') : unit_name
string += ', ' if string.size > 0
string += "#{units} #{substring}"
end
[seconds, string]
end
# Given seconds, prints out the number of years, months,
# days, hours, minutes, and seconds it took to complete.
# If the +seconds+ are insufficient to fulfill one of those
# units (e.g. year) then it isn't printed.
def formatted_time(seconds)
string = ''
seconds, string = time_unit(seconds, CenturySeconds, 'century', string)
seconds, string = time_unit(seconds, DecadeSeconds, 'decade', string)
seconds, string = time_unit(seconds, YearSeconds, 'year', string)
seconds, string = time_unit(seconds, MonthSeconds, 'month', string)
seconds, string = time_unit(seconds, DaySeconds, 'day', string)
seconds, string = time_unit(seconds, HourSeconds, 'hour', string)
seconds, string = time_unit(seconds, MinuteSeconds, 'minute', string)
seconds, string = time_unit(seconds, 1, 'second', string)
string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment