Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, why is 1.year.from_now not the same as 1.year.to_i.seconds.from_now?

Can I make Rails apply the same logic to my calculation in seconds as it does to my calculation in years?

puts "#{1.year.from_now} | #{1.year.to_i.seconds.from_now}"
 2017-03-23 18:48:06 UTC | 2017-03-24 00:48:06 UTC

I don’t understand where the 6-hour difference comes from.

like image 939
djb Avatar asked Mar 23 '16 18:03

djb


1 Answers

The difference is 6 hours. And it is because 1 year in seconds (as converted by the to_i method) is defined as 365.25 days in Ruby on Rails core extensions:

>> 1.year.to_i / 60 / 60 / 24.0
=> 365.25

Those 0.25 days is the actual 6 hours difference. By doing this, RoR is trying to count in the leap years which (by basic approximation) occur once in 4 years. The same is also evident from the years definition in Rails source code.

On the other hand 1.year.from_now does a shift of a concrete calendar datetime instead. As if you turned pages on your wall calendar.

like image 146
Matouš Borák Avatar answered Nov 09 '22 23:11

Matouš Borák