francis

Getting the number of months between two dates in Ruby/Rails - updated

posted Wednesday, 2 April 2008

Here lies the one that works, not the old one I posted ages ago. It also uses dates instead of timestamp differences and should therefore not break if you ask it to go before the Epoch (some time in 1970 I think):

Also see Adrien's comment left here (he's much cleverer than me!) - it's really trivial:

s is the start date and e is the end date (s is lower than e)

(e.month - s.month) + 12 * (e.year - s.year)

See!

module DateUtils

  class << self
    def months_between( date1=Time.now, date2=Time.now )

      date1 ||= Time.now
      date2 ||= Time.now

      if date1 > date2
        recent_date = date1.to_date

        past_date = date2.to_date
      else
        recent_date = date2.to_date

        past_date = date1.to_date
      end
      years_diff = recent_date.year - past_date.year

      months_diff = recent_date.month - past_date.month
      if months_diff < 0

        months_diff = 12 + months_diff
        years_diff -= 1

      end
      years_diff*12 + months_diff
    end

  end

end

links: digg this    del.icio.us    technorati