Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find average date from collection of dates (Ruby)

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.

like image 490
Karl Entwistle Avatar asked Feb 18 '10 10:02

Karl Entwistle


2 Answers

to_time.to_i

Is my friend ;)

like image 22
Karl Entwistle Avatar answered Sep 28 '22 05:09

Karl Entwistle


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)
like image 177
Hongli Avatar answered Sep 28 '22 05:09

Hongli