Skip to content

Instantly share code, notes, and snippets.

@larsthegeek
Created February 13, 2013 20:14
Show Gist options
  • Save larsthegeek/4947812 to your computer and use it in GitHub Desktop.
Save larsthegeek/4947812 to your computer and use it in GitHub Desktop.
A better function for producing a nice time diff
# 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