Skip to content

Instantly share code, notes, and snippets.

@wilsondealmeida
Last active June 28, 2018 11:50
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 wilsondealmeida/e5903ac9693c6df949256c06b68b1656 to your computer and use it in GitHub Desktop.
Save wilsondealmeida/e5903ac9693c6df949256c06b68b1656 to your computer and use it in GitHub Desktop.
Rails Integer to formatted time
Integer.class_eval do
def intftime(string = '%y-%m-%d %H:%M:%S')
seconds = dup.abs
time_values = {
'%y' => 60 * 60 * 24 * 30 * 12,
'%m' => 60 * 60 * 24 * 30,
'%d' => 60 * 60 * 24,
'%H' => 60 * 60,
'%M' => 60
}
['%y', '%m', '%d', '%H', '%M'].each do |item|
next unless string.include?(item)
total = 0
value = time_values[item]
if seconds >= value
total = seconds / value
seconds -= total * value
end
string.gsub!(item, total.to_s.rjust(2, '0'))
end
string.gsub!('%S', seconds.to_s.rjust(2, '0')) if string.include?('%S')
string
end
end
# > 100000.intftime('%H hours, %M minutes and %S seconds')
# => "27 hours, 46 minutes and 40 seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment