Get person's age in Ruby

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

    I believe this is functionally equivalent to @philnash's answer, but IMO more easily understandable.

    class BirthDate
      def initialize(birth_date)
        @birth_date = birth_date
        @now = Time.now.utc.to_date
      end
    
      def time_ago_in_years
        if today_is_before_birthday_in_same_year?
          age_based_on_years - 1
        else
          age_based_on_years
        end
      end
    
      private
    
      def age_based_on_years
        @now.year - @birth_date.year
      end
    
      def today_is_before_birthday_in_same_year?
        (@now.month < @birth_date.month) || ((@now.month == @birth_date.month) && (@now.day < @birth_date.day))
      end
    end
    

    Usage:

    > BirthDate.new(Date.parse('1988-02-29')).time_ago_in_years
     => 31 
    

提交回复
热议问题