Last active
August 29, 2015 14:07
-
-
Save rdetert/543524d668bcc56c54fa to your computer and use it in GitHub Desktop.
A quick and dirty helper method to display a short form distance of time in words.
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
# Usage: | |
# short_time_in_words(Time.now, 5.seconds.ago) # => "5s" | |
# short_time_in_words(Time.now, 5.minutes.ago) # => "5m" | |
# short_time_in_words(Time.now, 5.hours.ago) # => "5h" | |
# short_time_in_words(Time.now, 55.hours.ago) # => "2d" | |
# | |
def short_time_in_words(from_time, to_time) | |
from_time = from_time.to_i | |
to_time = to_time.to_i | |
diff = (from_time - to_time).abs | |
if diff < 60 | |
return "#{diff}s" | |
elsif diff < 60*60 | |
return "#{diff/60}m" | |
elsif diff < 60*60*24 | |
return "#{diff/(60*60)}h" | |
else | |
return "#{diff/(60*60*24)}d" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment