Last active
September 24, 2015 16:18
-
-
Save jonathansimmons/24fa43ac6ee53819fb93 to your computer and use it in GitHub Desktop.
A module to calculate human seconds with accuracy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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