Man*_*tas 122 ruby ruby-on-rails
我想从一个人的生日那里得到一个人的年龄.now - birthday / 365不起作用,因为有些年份有366天.我想出了以下代码:
now = Date.today
year = now.year - birth_date.year
if (date+year.year) > now
year = year - 1
end
Run Code Online (Sandbox Code Playgroud)
是否有更多Ruby的计算年龄的方法?
phi*_*ash 405
我知道我在这里参加派对的时间已经很晚了,但是当我试图计算出闰年2月29日出生的人的年龄时,接受的答案会非常糟糕.这是因为调用birthday.to_date.change(:year => now.year)创建了无效日期.
我使用以下代码(在Rails项目中):
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
Run Code Online (Sandbox Code Playgroud)
PJ.*_*PJ. 49
我发现这个解决方案运行良好,并且可供其他人阅读:
age = Date.today.year - birthday.year
age -= 1 if Date.today < birthday + age.years #for days before birthday
Run Code Online (Sandbox Code Playgroud)
容易,您不必担心处理闰年等.
Sad*_*egh 33
用这个:
def age
now = Time.now.utc.to_date
now.year - birthday.year - (birthday.to_date.change(:year => now.year) > now ? 1 : 0)
end
Run Code Online (Sandbox Code Playgroud)
Vik*_*ary 16
Ruby on Rails中的一个内核(ActiveSupport).处理闰年,闰秒等等.
def age(birthday)
(Time.now.to_s(:number).to_i - birthday.to_time.to_s(:number).to_i)/10e9.to_i
end
Run Code Online (Sandbox Code Playgroud)
逻辑从这里开始 - 用C#计算年龄
假设两个日期都在同一时区,如果utc()之前没有调用两个日期to_s().
(Date.today.strftime('%Y%m%d').to_i - dob.strftime('%Y%m%d').to_i) / 10000
Run Code Online (Sandbox Code Playgroud)
到目前为止的答案有点奇怪.您最初的尝试非常接近正确的方法:
birthday = DateTime.new(1900, 1, 1)
age = (DateTime.now - birthday) / 365.25 # or (1.year / 1.day)
Run Code Online (Sandbox Code Playgroud)
您将得到一个小数结果,所以随意将结果转换为整数to_i.这是一个更好的解决方案,因为它正确地将日期差异视为自事件以来以天(或相关时间类的情况下为秒)测量的时间段.然后根据一年中的天数进行简单划分即可得出年龄.以这种方式计算年龄时,只要保留原始DOB值,就不需要考虑闰年.
我的建议:
def age(birthday)
((Time.now - birthday.to_time)/(60*60*24*365)).floor
end
Run Code Online (Sandbox Code Playgroud)
诀窍是使用Time的减号操作返回秒
这个答案是最好的,请赞成。
我喜欢@philnash的解决方案,但条件可以更紧凑。布尔表达式的作用是使用字典顺序比较[month,day]对,因此可以只使用ruby的字符串比较:
def age(dob)
now = Date.today
now.year - dob.year - (now.strftime('%m%d') < dob.strftime('%m%d') ? 1 : 0)
end
Run Code Online (Sandbox Code Playgroud)