Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.