Skip to content

Instantly share code, notes, and snippets.

@remvee
Created November 30, 2012 12:22
Show Gist options
  • Select an option

  • Save remvee/4175478 to your computer and use it in GitHub Desktop.

Select an option

Save remvee/4175478 to your computer and use it in GitHub Desktop.
Function to create strings like "6d 4h 1h 34m 23s" from an amount of seconds.
# human_readable_seconds:
# s: "%{s}s"
# ms: "%{m}m %{s}s"
# hms: "%{h}h %{m}m %{s}s"
# dhms: "%{d}d %{h}h %{m}m %{s}s"
def human_readable_seconds(seconds)
attrs = {s: 60, m: 60, h: 24, d: nil}.reduce([1, {}]) do |(multiplier,result),(key,modulo)|
if seconds / multiplier > 0
if modulo
[multiplier * modulo, {key => (seconds / multiplier) % modulo}.merge(result)]
else
[multiplier, {key => (seconds / multiplier)}.merge(result)]
end
else
[multiplier, result]
end
end.last
I18n.t("human_readable_seconds.#{attrs.keys.join}", attrs)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment