Never been to DZone Snippets before?

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

Date.distance_to method for Ruby (See related posts)

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

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts