Rails TimeWithZone and Leap Years

Today is February 29th: the day our tests broke.

Our tests fail because these tests do things that, after all, can be compared to a command like this: Time.zone.now - 1.year + 1.year . And this is NOT NOT equal to Time.zone.now .

Why is this happening? Why is ActiveSupport unable to handle leap years in such calculations? Does this not work with timestamps, which will prevent this problem?

+5
source share
1 answer

You can use 4 years instead of 1 for the same effect. (Note: - 1. day, because now is March 1)

 (Time.zone.now - 1.day) - 4.year + 4.year => Mon, 29 Feb 2016 15:12:58 UTC +00:00 

It may be worth noting that (below), regardless of date.

 Time.zone.now => Tue, 01 Mar 2016 15:11:51 UTC +00:00 Time.zone.now == Time.zone.now - 1.year + 1.year => false 

If you are not using begin_of_day:

 (Time.zone.now - 1.day).beginning_of_day == ((Time.zone.now - 1.day) - 4.year + 4.year).beginning_of_day => true 

Also, it depends on what you are actually trying to do ... Why do you want to test Time.now - 1.year + 1.year ?

Also...

 1.year == 365.days => false 1.year == 365.25.days => true 
0
source

Source: https://habr.com/ru/post/1244128/


All Articles