Get person's age in Ruby

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

    This is a conversion of this answer (it's received a lot of votes):

    # convert dates to yyyymmdd format
    today = (Date.current.year * 100 + Date.current.month) * 100 + Date.today.day
    dob = (dob.year * 100 + dob.month) * 100 + dob.day
    # NOTE: could also use `.strftime('%Y%m%d').to_i`
    
    # convert to age in years
    years_old = (today - dob) / 10000
    

    It's definitely unique in its approach but makes perfect sense when you realise what it does:

    today = 20140702 # 2 July 2014
    
    # person born this time last year is a 1 year old
    years = (today - 20130702) / 10000
    
    # person born a year ago tomorrow is still only 0 years old
    years = (today - 20130703) / 10000
    
    # person born today is 0
    years = (today - 20140702) / 10000  # person born today is 0 years old
    
    # person born in a leap year (eg. 1984) comparing with non-leap year
    years = (20140228 - 19840229) / 10000 # 29 - a full year hasn't yet elapsed even though some leap year babies think it has, technically this is the last day of the previous year
    years = (20140301 - 19840229) / 10000 # 30
    
    # person born in a leap year (eg. 1984) comparing with leap year (eg. 2016)
    years = (20160229 - 19840229) / 10000 # 32
    

提交回复
热议问题