¿Cómo cambiar la zona horaria predeterminada para Active Record en Rails?


En mi application.rb me encontré con el siguiente comentario

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
 config.time_zone = 'Eastern Time (US & Canada)'

Como ven desde arriba, he hecho config.time_zone al tiempo EST. Sin embargo, aún cuando se crean registros en la base de datos, parece que datetime se está almacenando en formato UTC.

En el comentario anterior, dicen

...y hacer Active Record auto-convertir a esta zona...

¿Cómo puedo hacer eso, y dónde?

También, voy a implementar esto en heroku, así y me gustaría que la configuración para llevar

Author: user2262149, 2011-05-25

9 answers

Añadiendo lo siguiente a application.rb funciona

 config.time_zone = 'Eastern Time (US & Canada)'
 config.active_record.default_timezone = :local # Or :utc
 157
Author: Omnipresent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-11 07:55:03

He decidido compilar esta respuesta porque todas las demás parecen estar incompletas.

Config.active_record.default_timezone determina si se debe usar el tiempo.local (si se establece en: local) o Hora.utc (si se establece en :utc) al extraer fechas y horas de la base de datos. El valor predeterminado es: utc. http://guides.rubyonrails.org/configuring.html


Si desea cambiar Rails zona horaria, pero continuar teniendo Active Record guardar en la base de datos en UTC, utilice

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

Si desea cambiar Rails zona horaria Y tener Active Record almacenar tiempos en esta zona horaria, use

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

Advertencia : usted realmente debe pensar dos veces, incluso tres veces, antes de guardar los tiempos en la base de datos en un formato no UTC.

Nota
No olvide reiniciar su servidor Rails después de modificar application.rb.


Recuerde que config.active_record.default_timezone puede tomar solo dos valores

  • :local (convierte a la zona horaria definida en config.time_zone)
  • : utc (convierte a UTC)

Así es como puedes encontrar todas las zonas horarias disponibles

rake time:zones:all
 131
Author: Mihai-Andrei Dinculescu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-08 17:42:19

Llegué a la misma conclusión que Dean Perry después de mucha angustia. config.time_zone = 'Adelaide' y config.active_record.default_timezone = :local fue la combinación ganadora. Aquí está lo que encontré durante el proceso.

 34
Author: James Barona,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 02:39:53

En mi caso (Rails 5), terminé agregando estas 2 líneas en mi app/config/environments/development.rb

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

¡Eso es todo! Y para asegurarme de que Melbourne fue leído correctamente, ejecuté el comando en mi terminal:

bundle exec rake time:zones:all

Y Melbourne estaba listando en la zona horaria en la que estoy!

 16
Author: Carole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-13 20:22:51

Si desea establecer la zona horaria en UTC globalmente, puede hacer lo siguiente en Rails 4:

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

Asegúrese de reiniciar su aplicación o no verá los cambios.

 8
Author: sergserg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-05 01:32:21

En rails 4.2.2, vaya a application.rb y use config.time_zone='city' (por ejemplo:'Londres' o 'Bucarest' o 'Amsterdam' y así sucesivamente).

Debería funcionar bien. Funcionó para mí.

 2
Author: Andrei Laslo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-17 10:38:31

Tuve que añadir este bloque a mi archivo environment.rb y todo estaba bien:)

Rails.application.configure do
    config.time_zone = "Pacific Time (US & Canada)"
    config.active_record.default_timezone = :local
end
  • Lo agregué antes de la línea Rails.application.initialize!
 2
Author: Taylor A. Leach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-16 04:57:37

Para el usuario chino, simplemente agregue dos líneas a continuación config/application.rb:

config.active_record.default_timezone = :local
config.time_zone = 'Beijing'
 0
Author: Siwei Shen申思维,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 01:03:56

Si desea establecer la hora local, agregue el siguiente texto en application.rb

config.time_zone = 'Chennai'

# WARNING: This changes the way times are stored in the database (not recommended)
config.active_record.default_timezone = 'Chennai'

Luego reinicie su servidor

 -3
Author: Anand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-30 17:27:36