Skip to content

Instantly share code, notes, and snippets.

@rdetert
Last active August 29, 2015 14:07
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 rdetert/543524d668bcc56c54fa to your computer and use it in GitHub Desktop.
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.
# 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