Get person's age in Ruby

前端 未结 24 3075
忘了有多久
忘了有多久 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条回答
  •  萌比男神i
    2020-11-27 11:02

    Ok what about this:

    def age
      return unless dob
      t = Date.today
      age = t.year - dob.year
      b4bday = t.strftime('%m%d') < dob.strftime('%m%d')
      age - (b4bday ? 1 : 0)
    end
    

    This is assuming we are using rails, calling the age method on a model, and the model has a date database column dob. This is different from other answers because this method uses strings to determine if we are before this year's birthday.

    For example, if dob is 2004/2/28 and today is 2014/2/28, age will be 2014 - 2004 or 10. The floats will be 0228 and 0229. b4bday will be "0228" < "0229" or true. Finally, we will subtract 1 from age and get 9.

    This would be the normal way to compare the two times.

    def age
      return unless dob
      t = Date.today
      age = today.year - dob.year
      b4bday = Date.new(2016, t.month, t.day) < Date.new(2016, dob.month, dob.day)
      age - (b4bday ? 1 : 0)
    end
    

    This works the same, but the b4bday line is too long. The 2016 year is also unnecessary. The string comparison at the beginning was the result.

    You can also do this

    Date::DATE_FORMATS[:md] = '%m%d'
    
    def age
      return unless dob
      t = Date.today
      age = t.year - dob.year
      b4bday = t.to_s(:md) < dob.to_s(:md)
      age - (b4bday ? 1 : 0)
    end
    

    If you aren't using rails, try this

    def age(dob)
      t = Time.now
      age = t.year - dob.year
      b4bday = t.strftime('%m%d') < dob.strftime('%m%d')
      age - (b4bday ? 1 : 0)
    end
    

提交回复
热议问题