12

我有一个猜测表,每个猜测中只是一个日期。我想知道如何将两个或更多日期变成平均值。

<div id="logic">
<% foo = Date.today %>
<% bar = Date.today + 10 %>
<%= (foo + bar) / 2 %>

像这样的东西,但显然 Ruby 不会让我将两个日期分开。

4

2 回答 2

14

日期有点难处理,你应该使用时间。尝试将日期转换为时间:

require 'time'
foo_time = Time.parse(foo.to_s)
bar_time = Time.parse(bar.to_s)

将它们转换为时间戳,然后计算平均值,然后转换回时间:

avg = Time.at((foo_time.to_f + bar_time.to_f) / 2)

您可以将其转换回日期:

avg_date = Date.parse(avg.to_s)
于 2010-02-18T11:33:48.230 回答
2
to_time.to_i

是我的朋友 ;)

于 2010-02-18T11:04:35.343 回答