views:

152

answers:

4

I have to make a simple difference between two dates:

Date.parse("2009-06-20") - Date.today

This gives me the difference of the dates in days.

Anyone know a way to easily convert that to the following format:

The event occurred X years, Y months and Z days ago

Thank you.

+2  A: 

You may be looking for distance_of_times_in_words

Chubas
Good answer, but that's Ruby-on-Rails specific. The poster will have to extract that code in a pure ruby program. (He didn't mention Rails, so I presume it's a non-rails specific question.)
ghoppe
My bad, I'm using ruby-on-rails
robertokl
That's good, but I need something more precise. Do you know any other way?
robertokl
I guess it's pretty useful for most cases. The gem you found seems interesting, gonna check it out, thanks!
Chubas
A: 

I don't know of any standard, correct way to do this. As odd as it may seem the standard Ruby library has a Date class but no DateSpan functionality. Rails has a solution but it feels somewhat of a pain for me to require this whole mammoth for such a trivial task.

wilhelmtell
A: 

This is an example for difference in days, hours, seconds. Add the fields that you need.

def calculate_difference
  minutes = (Date.parse("2009-06-20") - Date.today).to_i / 60
  days = minutes / (24*60)
  minutes -= days * 24*60
  hours = minutes / 60
  minutes -= hours * 60
  "#{days}d#{hours}h#{minutes}m"
end
Kevin
not so pretty =/
Justin L.
yeah.. I would like to calculate the months and years too..
robertokl
The problem begins exactly with moths, because there are month with 28, 30 and 31 days..
robertokl