Created
May 22, 2009 18:48
-
-
Save jphastings/116290 to your computer and use it in GitHub Desktop.
A small Time class extension that gives a fuzzy time string output
This file contains 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
class Time | |
# Gives a 'fuzzy' output of the distance to the time stored. | |
# | |
# eg. 'in 28 minutes' or '23 hours ago' | |
def roughly | |
diff = self.to_i - Time.now.to_i | |
ago = diff < 0 | |
diff = diff.abs | |
case diff | |
when 0 | |
return "now" | |
when 1...60 | |
unit = "second" | |
when 60...3600 | |
diff = (diff/60).round | |
unit = "minute" | |
when 3600...86400 | |
diff = (diff/3600).round | |
unit = "hour" | |
when 86400...604800 | |
diff = (diff/86400).round | |
unit = "day" | |
when 604800...2592000 | |
diff = (diff/604800).round | |
unit = "week" | |
when 2592000...31557600 | |
diff = (diff/2592000).round | |
unit = "month" | |
else | |
diff = (diff/31557600).round | |
unit = "year" | |
end | |
unit += "s" if diff != 1 | |
return (ago) ? "#{diff} #{unit} ago" : "in #{diff} #{unit}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment