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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With