Forum: Ruby Day number delta

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-27 14:29
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
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-27 14: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
1b5341b64f7ce0244366eae17f06c801?d=identicon&s=25 Kirk Haines (Guest)
on 2006-04-27 15:22
(Received via mailing list)
On Thursday 27 April 2006 6:30 am, Lindsay Boyd 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 Haines
893c38bd5f182afc751540657d8aacf7?d=identicon&s=25 Stefano Taschini (Guest)
on 2006-04-27 15:31
(Received via mailing list)
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
This topic is locked and can not be replied to.