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

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

    How about something like:

    def years_diff(from_time,to_time)
      (((to_time - from_time).abs)/ (365 * 24 * 60 * 60)).to_i
    end
    
    years_diff(Time.now,Time.local(1950,03,22)) #=> 59
    years_diff(Time.now,Time.local(2009,03,22)) #=> 0
    years_diff(Time.now,Time.local(2008,03,22)) #=> 1
    

提交回复
热议问题