Get person's age in Ruby

2020-01-24 19:08发布

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:

now = Date.today
year = now.year - birth_date.year

if (date+year.year) > now
  year = year - 1
end

Is there a more Ruby'ish way to calculate age?

24条回答
混吃等死
2楼-- · 2020-01-24 19:51

I like this one:

now = Date.current
age = now.year - dob.year
age -= 1 if now.yday < dob.yday
查看更多
够拽才男人
3楼-- · 2020-01-24 19:51

DateHelper can be used to get years only

puts time_ago_in_words '1999-08-22'

almost 20 years

查看更多
聊天终结者
4楼-- · 2020-01-24 19:53
(Date.today.strftime('%Y%m%d').to_i - dob.strftime('%Y%m%d').to_i) / 10000
查看更多
疯言疯语
5楼-- · 2020-01-24 19:53

My suggestion:

def age(birthday)
    ((Time.now - birthday.to_time)/(60*60*24*365)).floor
end

The trick is that the minus operation with Time returns seconds

查看更多
别忘想泡老子
6楼-- · 2020-01-24 19:55

I know I'm late to the party here, but the accepted answer will break horribly when trying to work out the age of someone born on the 29th February on a leap year. This is because the call to birthday.to_date.change(:year => now.year) creates an invalid date.

I used the following code (in a Rails project) instead:

def age(dob)
  now = Time.now.utc.to_date
  now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end
查看更多
Explosion°爆炸
7楼-- · 2020-01-24 19:55

I had to deal with this too, but for months. Became way too complicated. The simplest way I could think of was:

def month_number(today = Date.today)
  n = 0
  while (dob >> n+1) <= today
    n += 1
  end
  n
end

You could do the same with 12 months:

def age(today = Date.today)
  n = 0
  while (dob >> n+12) <= today
    n += 1
  end
  n
end

This will use Date class to increment the month, which will deal with 28 days and leap year etc.

查看更多
登录 后发表回答