在一个区域中保存时间并在另一个区域中查看它们的标准是什么?我在environment.rb
:
config.time_zone = 'UTC'
但我想渲染它,并在其时区中执行“今天创建的所有帖子”之类的查询,其中beginning_of_day
以时区而不是UTC返回当天的开头。 rails是否已在后台处理转换?
问题在于:
@now = Time.now
=> Wed Jan 26 09:50:04 -0600 2011
User.count(:conditions => ["created_at > ?", @now])
SQL (1.3ms) SELECT count(*) AS count_all FROM `users` WHERE (created_at > '2011-01-26 09:50:04')
=> 1
@now = Time.now.utc
=> Wed Jan 26 15:50:10 UTC 2011
User.count(:conditions => ["created_at > ?", @now])
SQL (1.2ms) SELECT count(*) AS count_all FROM `users` WHERE (created_at > '2011-01-26 15:50:10')
=> 0
答案 0 :(得分:6)
ActiveSupport具有内置方法,可在任何时区显示时间值。通常,您会在用户模型中添加time_zone
列,并将其设置为用户的首选区域。
@user.update_attribute(:time_zone,'Eastern Time (US & Canada)')
然后在显示时间值时,将区域设置为用户的区域。
Time.zone = @user.time_zone
Time.zone.now # shows current time according to @user.time_zone
一种方法是在ApplicationController
中设置它,以便为每个请求完成:
class ApplicationController < ActionController::Base
before_filter :set_time_zone
def set_time_zone
Time.zone = current_user.time_zone if current_user
end
end
注意:请参阅ActiveSupport :: TimeWithZone
下的API