today = Date.today birth = date_of_birth(date_of_birth 也是一个 Date)
想要精确计算出年龄 x 岁 x 月 x 天
各位前辈们有什么好的方法么?
没法算出来。因为你没定义一个月按 30 天算还是 31 天算。
> years, days = ((Time.now - Time.new(1999, 01, 01))/3600/24).round.divmod(365)
=> [16, 290]
可以算出来,1999 年 01 月 01 日出生的人到今天是 16 岁 290 天。
year = 0.upto(100).find { |y| (y + 1).years.ago < birth }
month = 0.upto(11).find { |m| (m + 1).months.ago < birth + year.years }
day = 0.upto(30).find { |d| (d + 1).days.ago < birth + year.years + month.months }
直觉上可以数出来,不过比较低效
借位算术
born = Time.new 1999, 1, 1
now = Time.now
d = now.day - born.day
if underflow = (d < 0)
d += 30
end
m = now.month - born.month
m -= 1 if underflow
if underflow = (m < 0)
m += 12
end
y = now.year - born.year
y -= 1 if underflow
puts "#{y}岁#{m}月#{d}天"
或者 time diff hack:
born = Time.new 1999, 1, 1
now = Time.now
time_diff = Time.at(now - born + (born.year - 1970).years).utc
y, m, d, h, mm, s = time_diff.strftime("%Y %m %d %H %M %S").split.map &:to_i
puts "#{y-born.year}岁#{m-1}月#{d-1}天#{h}小时#{mm}分#{s}秒"
提供另外一個思路可以去 Wolphram Alpha 上面查 :
http://www.wolframalpha.com/input/?i=2000.02.29+to+2001.02.28