Get person's age in Ruby

前端 未结 24 3097
忘了有多久
忘了有多久 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:47

      def birthday(user)
        today = Date.today
        new = user.birthday.to_date.change(:year => today.year)
        user = user.birthday
        if Date.civil_to_jd(today.year, today.month, today.day) >= Date.civil_to_jd(new.year, new.month, new.day)
          age = today.year - user.year
        else
          age = (today.year - user.year) -1
        end
        age
      end
    

提交回复
热议问题