DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Date.distance_to Method For Ruby

05.26.2006
| 7457 views |
  • submit to reddit
        Gives years, months, and days between two dates (like a human would expect)

class Date
  def distance_to(end_date)
    years = end_date.year - year
    months = end_date.month - month
    days = end_date.day - day
    if days < 0
      days += 30
      months -= 1
    end
    if months < 0
      months += 12
      years -= 1
    end
    {:years => years, :months => months, :days => days}
  end
end