The information in this card is not entirely correct for recent versions of Rails. Please see our card on time zones in Rails 5+ for up-to-date information.
When working with times and dates in Rails applications, you need to deal with the following problem:
Time
objects have a time zone. You can get the zone name by doing time_object.zone
.Rails has two completely different modes of dealing with this.
We also prefer to use mode 1.
Time.now
or Time.parse
when saving or loading a record.date
on the shell. E.g. our main application servers are running on Berlin (CEST) time, but this will differ on other machines.datetime
fields in MySQL represent times in your local zone. E.g. Post.last.created_at.zone
will be "CEST" if your server is running in "CEST".Time.current
any more, since there's always a time zone (UTC). Actually, you cannot "turn off" time zones, just try to ignore them.In order to disable time zone conversion in Rails 2, open config/environment.rb
and comment or remove the config.time_zone line:
# config.time_zone = 'Berlin'
In order to disable time zone conversion in Rails 3 or newer, open config/application.rb
and add the following:
config.active_record.default_timezone = :local
config.active_record.time_zone_aware_attributes = false
keep the time zone set to your local time zone (i.e. "Berlin" for us).
Time
object in the configured zone, but stores them in MySQL as UTC times (regardless of the time zone you chose).Time.now
or Time.parse
will not be converted automatically when it is used for MySQL queries (because it is not a TimeWithZone
). You need to use Time.current
, Date.current
, DateTime.current
, Time.zone.parse
, etc. everywhere. You should read
this guide
Show archive.org snapshot
for a pretty exhaustive list of all the things you need to pay attention to.Time.now
or Time.parse
for you (e.g. a gem), you need to monkey patch this or be out of luck.rake time:zones:all
. The zone string for Germany is "Berlin".config.time_zone
is the default zone for a new application process. If your application should support user-configurable time zone, you can just set Time.zone = "..."
in a before_action
.In order to enable time zone conversion in either Rails 2 or Rails 3, open config/environment.rb
and define your time zone:
config.time_zone = 'Berlin'
Again, please read the working with time zones in Ruby on Rails Show archive.org snapshot from Elabs Show archive.org snapshot before you do anything in an application with time zones enabled.