Ruby 红宝石日期减法

Ruby 红宝石日期减法,ruby,date,datediff,Ruby,Date,Datediff,我对Ruby中的日期减法有问题 "2011-03-29".to_date - "2011-03-20".to_date #=> (9/1) ("2011-03-29".to_date - "2011-03-20".to_date).to_i #=> 9 似乎它返回了日期之间的天数差 现在我的问题是返回日期差的年、月、日数 ie ("2011-03-29".to_date - "2011-03-20".to_date) 应该回来 0 years, 0 month and 9 day

我对Ruby中的日期减法有问题

"2011-03-29".to_date - "2011-03-20".to_date #=> (9/1)
("2011-03-29".to_date - "2011-03-20".to_date).to_i #=> 9
似乎它返回了日期之间的天数差

现在我的问题是返回日期差的年、月、日数

ie ("2011-03-29".to_date - "2011-03-20".to_date)
应该回来

0 years, 0 month and 9 days
谢谢。

您可以尝试以下链接:

def time_diff_自然语言(from_time,to_time)
from_time=from_time.to_time如果是from_time.response_to?(:to_time)
to_time=to_time.to_time如果to_time.response_to?(:to_time)
距离(以秒为单位=((到时间-从时间).abs)。四舍五入
组件=[]
%w(年-月-周-日)。每个do间隔|
#对于每种间隔类型,如果剩余时间大于
#一个单位,计算剩余时间的单位数。
如果距离(以秒为单位)>=1.发送(间隔)
delta=(以秒为单位的距离/1.发送(间隔)).楼层
距离(以秒为单位)-=增量发送(间隔)
组件>2年6个月2天

参考资料:

我知道它有点脏,但你试过:

result = Date.new(0) + ("2011-03-29".to_date - "2011-03-20".to_date)
puts "#{result.year} years, #{result.month - 1} months and #{result.day} days"

您使用的是哪一个库或框架为字符串提供了迄今为止的
方法?轨道?还有别的吗?请不要防御性地编程?请详细说明。我知道它的意思。。。就像我有检查时间的方法一样。对吧塔斯???我想你错过了#{result.month-1},这是因为Date.new(0)将一月作为一个月。你是对的。月从1开始。我刚刚更新了答案。Tks。
result = Date.new(0) + ("2011-03-29".to_date - "2011-03-20".to_date)
puts "#{result.year} years, #{result.month - 1} months and #{result.day} days"