Days and Seconds
I’ve been bit more than once by something like this bit of Ruby (with Rails’ ActiveSupport extensions to Core):
yesterday = Date.today – 1.day
Seems innocent enough. We’re going to subtract one day from today to get yesterday’s date. But as of today, August 21, 2007, this code tells us that yesterday is 1771-01-30. 19th Century: I hardly knew ya.
Obviously 1.day isn’t a day. In fact, it’s the number of seconds in a day, which happens to be 86400. Go ahead, multiple 24 * 60 * 60 if you don’t believe me. The Date#- (minus) operator expects, sanely, a number of days. So we’re subtracting 86400 days. (Time#- expects seconds, but can’t go back too far in time, so it’s not always usable.)
Here’s the (obvious) answer:
yesterday = Date.today – 1
If I’m dealing with a larger number of days, say 3 years, I could multiple 365 (ignoring leap year rounding issues) by 3:
ye_good_old_days = Date.today – (365 * 3)
# or I do the math…
ye_good_old_days = Date.today – 1095 #3 years
Here’s another way, which is a little more verbose, but also a little more expressive:
ye_good_old_days = Date.today – (3.years / 1.day)
This gets the number of seconds in 3 years, then divides by the number of seconds in a day, to get the number of days in 3 years. I can take it or leave it.
Thoughts?
I found that you can also use 1.day.ago to get yesterday. This returns a Time instance, but you can easily convert it to a Date with 1.day.ago.to_date.