views:

213

answers:

2

Hey guys, 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 wont let me divide the two dates, any help much appreciated.

+2  A: 
to_time.to_i

Is my friend ;)

Karl Entwistle
+1  A: 

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
Great thanks for the help, thats awesome :)
Karl Entwistle