【发布时间】:2020-06-21 19:03:42
【问题描述】:
我需要创建一个计算年龄的方法,我可以按年计算,但如何准确地按日、月和年计算呢?
如果我今天做 - 生日我得到 12535/1
require 'date'
def age_in_days(day, month, year)
birthdate = Date.new(year, month, day)
today = Date.today
age = today.year - birthdate.year
return birthdate, today, age
end
puts age_in_days(12, 10, 1990)
【问题讨论】:
-
为了计算天数的差异,你看过修改后的儒略日数吗?例如
today.mjd - birthdate.mjd查看这个答案:stackoverflow.com/a/4502336/1611339 -
我不明白你的问题。我出生于 1915 年 2 月 12 日。如果今天的日期是 2020 年 3 月 13 日,答案会是 105 年、1 个月零 1 天,还是别的什么?如果是后者,你需要准确地描述你想要什么。
-
注意:在 Ruby 中,您不需要显式的
return,而是可以使用[ birthdate, today, age ]。
标签: ruby