Comparing Time
Dev tip 7/99
Comparing time values in code bit me when I was younger. Specifically, I struggled comparing a static time value to another time value that is relative to the current time. An example is programming a feature that sends an email three hours after a user signed up for an account. Countless bugs were fixed by a simple flip of either the < or > operator. Lucky for me a friend told me a tip that stopped my head from exploding.
Time Moves From Left to Right
The idea is to keep the time comparisons consistent with the statement that time moves from left to right on graphs. Here is a graph of CPU usage on a server where the previous statement is true.
Comparing time in code follows the same direction. Here’s how:
- Always use < or ≤ as the operator
- The left operand is the value on the right side of time
- The right operand is the value on the left side of time
Below I show the different ways I can compare time using this tip.
Keeping with the email example above — send email at least 3 hours after a user signed up:
Time.now + 3*60*60 < user.created_at
Send an email within 3 hours after a user signed up:
user.created_at <= Time.now + 3*60*60
Find the number of users signed up within the last two hours:
Time.now — 2*60*60 <= user.created_at
Find the number of users signed up before 6 hours ago:
user.created_at < 6*60*60
I like using this tip because it helps keep me consistent. Hopefully, it helps you too!