Created
February 13, 2013 20:14
-
-
Save larsthegeek/4947812 to your computer and use it in GitHub Desktop.
A better function for producing a nice time diff
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
# produces [year, month, day, hour, minute, second] | |
# from time is the older date | |
def time_diff(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) | |
components = [] | |
%w(year month day hour minute second).map do |interval| | |
distance_in_seconds = (to_time.to_i - from_time.to_i).round(1) | |
delta = (distance_in_seconds / 1.send(interval)).floor | |
delta -= 1 if from_time + delta.send(interval) > to_time | |
from_time += delta.send(interval) | |
components << pluralize(delta, interval) | |
delta | |
end | |
components.join(', ') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment