Skip to content

Instantly share code, notes, and snippets.

@jonathansimmons
Last active September 24, 2015 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathansimmons/24fa43ac6ee53819fb93 to your computer and use it in GitHub Desktop.
Save jonathansimmons/24fa43ac6ee53819fb93 to your computer and use it in GitHub Desktop.
A module to calculate human seconds with accuracy.
module WMUtility
class Calculate
# modified from http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails#answer-4136485
def self.human_seconds(secs, options={})
options = {
seconds: false,
minutes: true,
hours: true,
days: true,
}.merge(options)
# Collect sections
values = [[60, "second"], [60, "minute"], [24, "hour"], [1000, "day"]].map do |count, name|
if secs.present? && secs > 0
secs, n = secs.divmod(count)
"#{ActionController::Base.helpers.pluralize(n.to_i, name)}" if options["#{name}s".to_sym] && n.to_i > 0
end
end
# Return human string or nil
values.compact.reverse.join(' ')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment