我目前有一个不太理想的解决方案:
def years_between_dates(date_from, date_to)
((date_to.to_time - date_from.to_time) / 1.year.seconds).floor
end
计算不必是精确的(有leap年等),但需要相当准确并考虑数月。 3.8年应返回3年,因此
floor
。我将
to_time
转换为Date
,Time
和DateTime
。我禁不住认为有一种更简洁的方法可以完成上述操作。
最佳答案
好像您的实际上是最优雅的方式。
即使在distance_of_time_in_words
rails的定义中,它也具有:
distance_in_minutes = ((to_time - from_time) / 60.0).round
distance_in_seconds = (to_time - from_time).round
Reference
更好的版本可能是:
def years_between_dates(date_from, date_to)
((date_to - date_from) / 365).floor
end
关于ruby-on-rails - 一种计算Rails中两个日期之间的年数的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967203/