Rails, timezones and the current date – an awkward combination
Posted on: Wednesday, Jan 9, 2019
Working with time zones in Rails sometimes requires a bit knowledge and persistence to get it right; I learned that this is something you can easily do wrong.
Ask a random Ruby developer to get today’s Date. He will most likely respond with Date.today
. And what about the current time? He’ll probably say Time.now
. Both are correct… for Ruby that is.
In Rails it may be correct as well until you need to handle different time zones. Most developers actually think they don’t need to (because they do not need to use a different time zone in their application) until they run into problems. For example, most applications do need to work with the transition of daylight saving (and thus requires a timezone setting in the configuration) or the database actually works with a different timezone then the application (usually UTC).
So what if you can’t use Date.today
 and Time.now
, what do you need to use? Well Rails supplies the current
 method on Rails’s Date
and Time
 classes to fix this issue. This method checks whether you’re using timezones (in your configuration) and if you are, it uses the Time.zone
 variant.
So a good rule of thumb is to always use Date.current
, Time.current
 or DateTime.current
 (although Rubocop recommends not to use the latter) for getting the current time or date.
More information can be found in the following articles:
- Tags: current, development, rails, ruby, timezone, today, utc
- No Comments