Created
February 13, 2013 19:58
-
-
Save larsthegeek/4947647 to your computer and use it in GitHub Desktop.
Nice fx to get a time span in natural language
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
# from http://stackoverflow.com/questions/1065320/in-rails-display-time-between-two-dates-in-english | |
def time_diff_in_natural_language(from_time, to_time) | |
from_time = from_time.to_time if from_time.respond_to?(:to_time) | |
to_time = to_time.to_time if to_time.respond_to?(:to_time) | |
distance_in_seconds = ((to_time - from_time).abs).round | |
components = [] | |
%w(year month week day).each do |interval| | |
# For each interval type, if the amount of time remaining is greater than | |
# one unit, calculate how many units fit into the remaining time. | |
if distance_in_seconds >= 1.send(interval) | |
delta = (distance_in_seconds / 1.send(interval)).floor | |
distance_in_seconds -= delta.send(interval) | |
components << pluralize(delta, interval) | |
end | |
end | |
components.join(", ") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment