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):

Adrie’s comment left on my old blog pointed this out (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

      (past_date.month - recent_date.month) + 12 * (recent_date.year - past_date.year)

    end

  end

end

Imported Comments:

UE

Thanks a lot. helped me much

john

not working

fdsa

doesnt this neglect the actual day of the month? there isn’t 1 month between 2/1/11 and 1/31/11, but this would claim there is…

Francis

ok – but “months or part therof” is a long method name 🙂