How to calculate how many years passed since a given date in Ruby?

前端 未结 13 2206
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 16:33

This question was here for other languages, so let here be one for Ruby.

How do I calculate number of complete years that have passed from a given date? As you prob

13条回答
  •  独厮守ぢ
    2020-12-09 16:52

    How about this:

    def age_in_years(date)
      # Difference in years, less one if you have not had a birthday this year.
      today = Date.today
      age = today.year - date.year
      age = age - 1 if [date.day, date.month, today.year].join('/').to_date > Date.today
    end
    

提交回复
热议问题