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
on 2006-04-27 16:29
on 2006-04-27 16:53
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 2006-04-27 17:22
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.
on 2006-04-27 17:31
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