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

前端 未结 13 2201
被撕碎了的回忆
被撕碎了的回忆 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 17:08

    I think this will always work, even for someone with a birthday near a leap day:

    require 'date'
    
    def calculate_age(start_date, end_date)
      end_date.year - start_date.year - ((end_date.month > start_date.month || (end_date.month == start_date.month && end_date.day >= start_date.day)) ? 0 : 1)
    end
    
    puts calculate_age( Date.strptime('03/02/1968', '%m/%d/%Y'), Date.strptime('03/02/2010', '%m/%d/%Y'))
    

    The calculated age with this method in the example call above is 42, which is correct despite 1968 being a leap year and the birthday being near a leap day.

    Plus, this way there is no need to create a local variable.

提交回复
热议问题