Get person's age in Ruby

前端 未结 24 2969
忘了有多久
忘了有多久 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 10:54

    I think it's alot better to do not count months, because you can get exact day of a year by using Time.zone.now.yday.

    def age
      years  = Time.zone.now.year - birthday.year
      y_days = Time.zone.now.yday - birthday.yday
    
      y_days < 0 ? years - 1 : years
    end
    

提交回复
热议问题