Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default timezone for Active Record in Rails?

People also ask

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


I have decided to compile this answer because all others seem to be incomplete.

config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc. http://guides.rubyonrails.org/configuring.html


If you want to change Rails timezone, but continue to have Active Record save in the database in UTC, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'

If you want to change Rails timezone AND have Active Record store times in this timezone, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local

Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.

Note
Do not forget to restart your Rails server after modifying application.rb.


Remember that config.active_record.default_timezone can take only two values

  • :local (converts to the timezone defined in config.time_zone)
  • :utc (converts to UTC)

Here's how you can find all available timezones

rake time:zones:all

adding following to application.rb works

 config.time_zone = 'Eastern Time (US & Canada)'
 config.active_record.default_timezone = :local # Or :utc

I came to the same conclusion as Dean Perry after much anguish. config.time_zone = 'Adelaide' and config.active_record.default_timezone = :local was the winning combination. Here's what I found during the process.


In my case (Rails 5), I ended up adding these 2 lines in my app/config/environments/development.rb

config.time_zone = "Melbourne"
config.active_record.default_timezone = :local

That's it! And to make sure that Melbourne was read correctly, I ran the command in my terminal:

bundle exec rake time:zones:all

and Melbourne was listing in the timezone I'm in!


If you want to set the timezone to UTC globally, you can do the following in Rails 4:

# Inside config/application.rb
config.time_zone = "UTC"
config.active_record.default_timezone = :utc

Be sure to restart your application or you won't see the changes.


On rails 4.2.2, go to application.rb and use config.time_zone='city' (e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).

It should work just fine. It worked for me.