Open up a Rails console and enter this:
2.weeks.ago.between? 2.weeks.ago, 1.week.ago
Did it give you true or false? No really, try it a few more times and it will give you different answers.
Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.
I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.
However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.
Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.
Oddly enough, this doesn't happen when doing:
Date.yesterday.between? Date.yesterday, Date.tomorrow
The cause is undoubtedly due to the resolution of the time function. Sometimes the two instances of 2.weeks.ago resolve to the same time and sometimes they don't. When you use yesterday you don't see the issue because it always resolves to zero hour instead of relative to the current time.
In a case like yours you probably only want to compare the date, not the date and time.
tvanfosson, hit it on the head.
2.weeks.ago gives you a time exactly two weeks from the execution to the millisecond. So evaluating it twice could provide two different times.
Doing something like the following would give you consistent results:
two_weeks_ago = 2.weeks.ago two_weeks_ago.between? two_weeks_ago, 1.week.ago
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With