Strange behavior when used in between? method for dates

Open the Rails console and enter the following:

2.weeks.ago.between? 2.weeks.ago, 1.week.ago

Did it give you truth or falsehood? No, try a few more times and it will give you different answers.

Now I think that since we are comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements causes this behavior.

I can’t say for sure, but I guess in between? the method is not inclusive, and therefore, if several milliseconds have passed between the two operators, the above code will be evaluated as true, because it will be between two matched dates.

However, if the processor manages to process it fast enough so that the elapsed time is clueless, it will be evaluated as false.

Can anyone shed some light on this? This is an extreme case at best in a system where it can be crucial, but it gave me a headache when my tests passed and did not seem random.

Oddly enough, this does not happen:

 Date.yesterday.between? Date.yesterday, Date.tomorrow
+3
source share
5 answers

The reason, of course, is due to the resolution of the time function. Sometimes two instances of 2.weeks.ago resolve at the same time, and sometimes not. When you use yesterday, you do not see the problem, because it always resolves the zero hour instead of the current time.

In a case like yours, you probably want to compare the date, not the date and time.

+5
source

tvanfosson, hit him on the head.

2.weeks.ago . .

- :

two_weeks_ago = 2.weeks.ago
two_weeks_ago.between? two_weeks_ago, 1.week.ago
+1

. ? b/c, DB.

+1

- , thwt 2.weeks.ago , , - . . , . , , , , .

0

:

two_weeks_ago = 2.weeks.ago.to_date
two_weeks_ago.between? two_weeks_ago, 1.week.ago
0

All Articles