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.
to_time.to_i
Is my friend ;)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With