Ethan
Ethan

Reputation: 60089

How can I find how many days apart two Dates are?

I have an ActiveRecord model with some attributes stored in MySQL as DATEs. In Ruby, they appear as Dates.

How can I discover how many days apart they are, assuming like March 3, 2011 is one day apart from March 4, 2011, two days apart from March 5, etc.

Also, I need to find out how many days apart they are from the current date.

Upvotes: 1

Views: 489

Answers (3)

Ethan
Ethan

Reputation: 60089

After looking around a little more I came up with this...

(obj.arrival_date - obj.departure_date).floor.abs
 # => How many days apart.

And...

(obj.arrival_date - Date.today).floor.abs

Based on experimentation, it seems to work, although I'm not 100 percent sure it will always be correct.

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107728

Use the distance_of_time_in_words helper:

distance_of_time_in_words(date1, date2)

If you want greater accuracy, I wrote a gem called dotiw which would allow something like this:

distance_of_time_in_words(date1, date2, false, :only => ["days"]

Upvotes: 1

Zepplock
Zepplock

Reputation: 29145

Date.new(2001,2,3) - Date.new(1999,2,3)

will give number of days

Upvotes: 0

Related Questions