Day number delta

How can I calculate the number of days between two Date objects?. This
is easy enough with Time objects using the epoch seconds method tv_sec.
Is there something similar for Dates?

thanks
Lindsay

Searching the web, I’ve seen this suggested:

(Date.parse(date2.to_s) - Date.parse(date1.to_s)).to_i

but this strikes me as plain ugly! Surely there is a much better
solution…

Lindsay

On Thursday 27 April 2006 6:30 am, Lindsay B. wrote:

How can I calculate the number of days between two Date objects?. This
is easy enough with Time objects using the epoch seconds method tv_sec.
Is there something similar for Dates?

delta = a - b

Just subtract one from the other.

irb(main):001:0> require ‘date’
=> true
irb(main):002:0> a = Date.new(2006,4,28)
=> #<Date: 4907707/2,0,2299161>
irb(main):003:0> b = Date.new(2005,3,17)
=> #<Date: 4906893/2,0,2299161>
irb(main):004:0> c = a - b
=> Rational(407, 1)
irb(main):005:0> c.to_i
=> 407

Kirk H.

You might want to require mathn as well:

require ‘date’
require ‘mathn’

Date.new(2006,4,28) - Date.new(2005,3,17)
#=> 407

Ciao,
Stefano