How can I find the number of days between two Date objects in Ruby ?

How can I find the number of days between two Date objects in Ruby ?

Asked on December 17, 2018 in Ruby.
Add Comment


  • 6 Answer(s)

    In order to get the solution, we have to subtract the beginning date from the end date:

    endDate - beginDate
    
    
    Answered on December 17, 2018.
    Add Comment
    irb(main):005:0> a = Date.parse("12/1/2010")
    => #<Date: 4911063/2,0,2299161>
     
    irb(main):007:0> b = Date.parse("12/21/2010")
    => #<Date: 4911103/2,0,2299161>
     
    irb(main):016:0> c = b.mjd - a.mjd
    => 20
    

    This code can be uses a Modified Julian Day Number.

    For more reference .

    The interval of time in days and fractions of a day since January 1, 4713 BC Greenwich noon, Julian proleptic calendar is Julian date.

     

    Answered on December 17, 2018.
    Add Comment

    Use this code to get answer,

    > endDate = Date.new(2014, 1, 2)
    => #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)>
    > beginDate = Date.new(2014, 1, 1)
    => #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)>
    > days = endDate - beginDate
    => (1/1)
    > days.class
    => Rational
    > days.to_i
    => 1
    

     

    Answered on December 17, 2018.
    Add Comment
    endDate - beginDate 
    Answered on May 20, 2019.
    Add Comment
    2.0.0-p195 :005 > require 'date'
     => true 
    2.0.0-p195 :006 >  a_date = Date.parse("25/12/2013")
     => #<Date: 2013-12-25 ((2456652j,0s,0n),+0s,2299161j)> 
    2.0.0-p195 :007 >  b_date = Date.parse("10/12/2013")
     => #<Date: 2013-12-10 ((2456637j,0s,0n),+0s,2299161j)> 
    2.0.0-p195 :008 > a_date-b_date
     => (15/1) 
    Answered on May 20, 2019.
    Add Comment
     endDate = Date.new(2014, 1, 2)
     => #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)> 
    > beginDate = Date.new(2014, 1, 1)
     => #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)> 
    > days = endDate - beginDate
     => (1/1) 
    > days.class
     => Rational 
    > days.to_i
     => 1 
    Answered on May 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.