如何计算Ruby中给定日期以来已经过去了多少年? [英] How to calculate how many years passed since a given date in Ruby?

查看:185
本文介绍了如何计算Ruby中给定日期以来已经过去了多少年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在这里是为其他语言,所以让这里是一个Ruby。

This question was here for other languages, so let here be one for Ruby.

如何计算从给定日期过去的完整年份数?你可能已经猜到了,那就是自动计算人的年龄。最近的一个是 distance_of_time_in_words Rails帮手,所以以下模板

How do I calculate number of complete years that have passed from a given date? As you probably have guessed, that's to calculate person's age automatically. The closest one is distance_of_time_in_words Rails helper, so the following template

Jack is <%= distance_of_time_in_words (Time.now, Time.local(1950,03,22)) %> old.

Jack is over 59 years old.

但是我需要更精确的函数,只产生数字。有没有一个?

But I need more precise function that yields just number. Is there one?

如果存在某种Ruby on Rails帮助器函数,这是可以的,虽然纯Ruby解决方案会更好。

If there exists some kind of Ruby on Rails helper function for this, this is OK, although pure Ruby solution would be better.

编辑:问题的要点是需要非近似解决方案。在3月2日的第二天,Jack应该是59岁,第二天他应该是60岁。闰年等应考虑在内。

the gist of the question is that a non-approximate solution is needed. At the 2nd of March Jack should be 59 years old and the next day he should be 60 years old. Leap years and such should be taken into account.

推荐答案

你正在寻找一个精确的时间量度吗?如果是前者,就没有必要担心闰年和其他并发症。您只需要计算年数差异,如果该人今年还没有生日,则减少它。如果是后者,则可以将秒数转换成多年,如其他答案所示。

Do you want age as people typically understand it, or are you looking for a precise measure of time elapsed? If the former, there is no need to worry about leap years and other complications. You simply need to compute a difference in years and reduce it if the person has not had a birthday yet this year. If the latter, you can convert seconds elapsed into years, as other answers have suggested.

def age_in_completed_years (bd, d)
    # Difference in years, less one if you have not had a birthday this year.
    a = d.year - bd.year
    a = a - 1 if (
         bd.month >  d.month or 
        (bd.month >= d.month and bd.day > d.day)
    )
    a
end

birthdate = Date.new(2000, 12, 15)
today     = Date.new(2009, 12, 14)

puts age_in_completed_years(birthdate, today)

这篇关于如何计算Ruby中给定日期以来已经过去了多少年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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