12

I have a table of guesses, within each guess is just a date. I was wondering how I would go about turning two or more dates into an average.

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

Something like this, but obviously Ruby won't let me divide the two dates.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Karl Entwistle
  • 933
  • 2
  • 13
  • 25
  • What does the average of two dates mean in the real world? Are you tring to find the date half way between two dates? If you had 100 dates, what would their average be conceptually? – Simon Feb 18 '10 at 10:52
  • Maybe its easier if I link to the site, http://www.expct.info/products/3 you can see the two dates 2010-03-18 and 2010-02-18, id like to output the average of the two and harness the wisdom of crowds, the more people vote the closer to the actually date of the iPads release it *should* get. I guess the average within my example would be Date.today + 5 – Karl Entwistle Feb 18 '10 at 11:07

2 Answers2

14

Date is a bit hard to work with, you should use Time. Try converting the Dates into Times:

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

Convert them to timestamps, then calculate the average, then convert back to Time:

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

You can convert that back to Date:

avg_date = Date.parse(avg.to_s)
Hongli
  • 18,682
  • 15
  • 79
  • 107
2
to_time.to_i

Is my friend ;)

Karl Entwistle
  • 933
  • 2
  • 13
  • 25