我正在使用Rails 4.我已经从数据库中读取了2条记录( b1 和 b2 )。它们都有一个名为build_start_time
的列,在Mysql中定义为datetime
类型。 b1 记录与 b2 记录之间的build_start_time
是这样的:
2.0.0-p643 :021 > b1.build_start_time
=> Tue, 12 Aug 2014 18:23:31 UTC +00:00
2.0.0-p643 :012 > b2.build_start_time
=> Fri, 15 Aug 2014 10:07:18 UTC +00:00
如何在Rails中计算它们之间的持续时间?有人有想法吗? 结果应该是这样的:
b2.build_start_time - b1.build_start_time = 2 days 15 hours 53 minutes 47 seconds
这可能吗?
答案 0 :(得分:1)
假设您可以在不到一秒的时间内拒绝您的答案,您可以尝试使用to_i
和ago
方法:
def datetime_diff(datetime1, datetime2)
res = datetime1 <=> datetime2
if res == 0
# order doesn't matter in this case
min = datetime1
max = datetime2
elif res < 0
min = datetime1
max = datetime2
else
min = datetime2
max = datetime1
end
max.ago(min.to_i) # min.to_i returns min in seconds since the epoch
end
你弄清楚哪个时间先到,然后你返回两次x秒ago
中的较晚时间,其中x是自纪元以来的较早时间(以秒为单位)。见http://api.rubyonrails.org/classes/DateTime.html#method-i-3C-3D-3E