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

前端 未结 13 2246
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 17:01

    Do you want age as people typically understand it, or are you looking for a precise measure of time elapsed? If the former, there is no need to worry about leap years and other complications. You simply need to compute a difference in years and reduce it if the person has not had a birthday yet this year. If the latter, you can convert seconds elapsed into years, as other answers have suggested.

    def age_in_completed_years (bd, d)
        # Difference in years, less one if you have not had a birthday this year.
        a = d.year - bd.year
        a = a - 1 if (
             bd.month >  d.month or 
            (bd.month >= d.month and bd.day > d.day)
        )
        a
    end
    
    birthdate = Date.new(2000, 12, 15)
    today     = Date.new(2009, 12, 14)
    
    puts age_in_completed_years(birthdate, today)
    

提交回复
热议问题