Home > Mobile >  How can I find the average of 3 date in Ruby on rails or Ruby?
How can I find the average of 3 date in Ruby on rails or Ruby?

Time:03-17

How can I find the average of 3 date in Ruby on rails or Ruby ? like bellow.

(Date1 Date2 Date3)/3

CodePudding user response:

If you convert the dates to integers with .to_i you can do the average exactly as you suggested. Then use .at to get back to a datetime.

d1 = Time.now
=> 2022-03-16 11:07:12 -0700

d2 = Time.now - 10000
=> 2022-03-16 08:20:32 -0700

d3 = Time.now - 30000
=> 2022-03-16 02:47:12 -0700

Time.at((d1.to_i   d2.to_i   d3.to_i)/3)
=> 2022-03-16 07:24:58 -0700

CodePudding user response:

If you are working with Date objects (Not Time nor DateTime) you can easily calculate the middle date between 3 (or even more dates if you add them to the array).

Imagine you have your dates in an array:

dates = [Date.today, 1.day.ago, 10.days.ago]
difference = dates.max - dates.min
average_date = dates.min   difference/2

Basically, we're getting the days difference between the higher date value and the minimum date value, then adding half that difference to the smallest date, and there you have the average date between the 3, the date in the middle won't change anything so it's not being used with this approach.

  • Related