在 Ruby 中获取人的年龄 [英] Get person's age in Ruby

查看:14
本文介绍了在 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'ish 的方法来计算年龄?

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

这篇关于在 Ruby 中获取人的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆