Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Set config.time_zone to the server's time zone?

For compatibility reasons I need to store and display all dates in the server's local time zone. To do this I configured the rails application like this in application.rb:

# Do not convert database DATETIME / DATE columns to UTC:
config.active_record.default_timezone = :local

It works okay when I store dates they are stored in the server's local timezone. However when retrieving the data Rails converts it to UTC, so for example Post.find(1).posted returns 2016-02-02 18:06:48 UTC but it is actually stored as 2016-02-02 13:06:48 in the database.

How can I keep Rails from converting it to UTC?

I thought that setting the application time zone to the server's local time zone will help so I wanted to set config.time_zone to the server's local time zone and tried with:

config.time_zone = Time.now.zone

But the problem with it is that it returns a three character timezone code like COT and config.time_zone is expecting a Time Zone name like Bogota

How can I translate the three character code to the full time zone name? or, how can I get the local time zone name? or, how can I configure Rails to not convert the database dates to UTC?

like image 573
Sergio Avatar asked Jan 07 '23 17:01

Sergio


1 Answers

Just enter "Bogota" as the string for config.time_zone and with config.active_record.default_timezone set to :local you should get what you need. DB in local timezone (which, I hope, is Bogata's TZ) and the model attributes in Bogata's TZ too.

Update

Based on a comment, the OP wants to be able to set the timezone in Ubuntu at an OS level and then use that setting to configure Rails without any additional step.

So @Sergio, the good news is that you can set config.time_zone to the IANA timezone name that you'd be familiar with in using the Ubuntu tools, ie. you can do:

config.time_zone = "America/Bogota"

So all you need to do is work out how to get that from your OS, I think it should be the contents of /etc/timezone so:

config.time_zone = File.read("/etc/timezone").chomp
like image 84
smathy Avatar answered Jan 15 '23 15:01

smathy