我需要关闭Rails应用程序和Mysql之间的时间转换。
此评论位于ActiveRecord source说:
# Timestamps are in UTC by default but you can use the local timezone by setting:
#
# config.active_record.default_timezone = :local
但是,我的服务器使用 UTC
时区,如果使用 :local
或 :utc
选项,则没有什么区别。所需的时区是'Brasilia'
。
生产服务器上的 Rails 控制台显示转换:
$ RAILS_ENV=production bundle exec rails c
Loading production environment (Rails 4.1.4)
2.0.0 :001 > Time.current
=> Wed, 13 Aug 2014 17:34:15 BRT -03:00
2.0.0 :002 > Schedule.where(startDateTimeSchedule: Time.current)
Schedule Load (1.0ms) SELECT `Schedule`.* FROM `Schedule` WHERE `Schedule`.`startDateTimeSchedule` = '2014-08-13 20:34:25'
附注:accepted answer关于此主题的高票数问题的部分内容是错误的。
最佳答案
您可以在 config/application.rb 中设置新的默认时区
config.time_zone = 'Brasilia'
如果您知道用户的时区,您还可以通过将此代码添加到您的 ApplicationController 来正确转换他们
around_filter :user_time_zone, :if => :current_user
def user_time_zone(&block)
Time.use_zone(current_user.timezone, &block)
end
关于mysql - 如何更改 ActiveRecord 时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295676/