A few minutes ago I had a problem in production in a scheduled job that was working for more than a year now, the problem was that a new user scheduled it for 22:00 GMT -3, what hadn’t happened before.
The code had tests, but we usually do not work around this time and the tests automated tests never were executed this late at night.
That scheduled job used to define the contents of a message Date.yesterday, and that being executed at 22:00 GMT-3, was really being executed at 01:00 GMT.
And this caused Date.yesterday to actually be today at 00:00.
The solution was actually simple, but really hard to test, since the problem only happens if the scheduled time in the user time zine was tomorrow GMT.
So every time you are using any type of date and time in your code, remember to surround it with this simple snippet that will save your life!
Time.use_zone(current_user.timezone) do # Here it is safe to use Date.yesterday, and any relative date and time codes end
If you are using Rails, and you can configure a timezone for the application (what is not my situation, because each user has a different timezone), you can simply change ” config.time_zone ” in your environment or config/application.rb
For one timezone for each user, you can for example add an around filter in the ApplicationController like this:
around_action :user_timezone def user_timezone Time.use_zone(current_user.timezone) do yield end end
And if I did that before (not exactly that, but the idea is the same) I wouldn’t have had the production problem from today…
So I hope this post can help prevent the same problem in your application.