在Ruby中获取人的年龄
问题描述:
我想从生日中获取一个人的年龄.now -birthday/365
不起作用,因为有些年份有 366 天.我想出了以下代码:
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
是否有更像 Ruby 风格的方法来计算年龄?
Is there a more Ruby'ish way to calculate age?
答
我知道我在这里参加聚会迟到了,但是在尝试计算 2 月 29 日出生的人的年龄时,已接受的答案会崩溃闰年.这是因为对 birthday.to_date.change(:year => now.year)
的调用创建了一个无效的日期.
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.
我改用以下代码:
require 'date'
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