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.

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.


Need Your Help

How to optimize routine with large file I/O (read, writes) and computation?

c# performance .net-4.0

I know they say premature optimization is the root of all evil... but it's about that time.

How do I autowire a Spring TaskExecutor created thread?

java multithreading spring autowired

According to Spring's documentation the way to use the TaskExecutor is as follows: