Get person's age in Ruby

前端 未结 24 3080
忘了有多久
忘了有多久 2020-11-27 10:32

I\'d like to get a person\'s age from its birthday. now - birthday / 365 doesn\'t work, because some years have 366 days. I came up with the following code:

24条回答
  •  伪装坚强ぢ
    2020-11-27 11:06

    To account for leap years (and assuming activesupport presence):

    def age
      return unless birthday
      now = Time.now.utc.to_date
      years = now.year - birthday.year
      years - (birthday.years_since(years) > now ? 1 : 0)
    end
    

    years_since will correctly modify the date to take into account non-leap years (when birthday is 02-29).

提交回复
热议问题