Get person's age in Ruby

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

    The answers so far are kinda weird. Your original attempt was pretty close to the right way to do this:

    birthday = DateTime.new(1900, 1, 1)
    age = (DateTime.now - birthday) / 365.25 # or (1.year / 1.day)
    

    You will get a fractional result, so feel free to convert the result to an integer with to_i. This is a better solution because it correctly treats the date difference as a time period measured in days (or seconds in the case of the related Time class) since the event. Then a simple division by the number of days in a year gives you the age. When calculating age in years this way, as long as you retain the original DOB value, no allowance needs to be made for leap years.

提交回复
热议问题