Ruby on rails 在UTC中保存日期时间,在Rails中查看/查询用户时区?

Ruby on rails 在UTC中保存日期时间,在Rails中查看/查询用户时区?,ruby-on-rails,timezone,Ruby On Rails,Timezone,在一个区域中保存时间并在另一个区域中查看时间的标准是什么?我的环境中有这个。rb: 但我想呈现它,并像今天在时区中创建的所有帖子一样进行查询,其中开始的日期返回在时区中的一天的开始,而不是UTC。rails已经在后台处理转换了吗 问题是: @now = Time.now => Wed Jan 26 09:50:04 -0600 2011 User.count(:conditions => ["created_at > ?", @now]) SQL (1.3ms) S

在一个区域中保存时间并在另一个区域中查看时间的标准是什么?我的环境中有这个。rb:

但我想呈现它,并像今天在时区中创建的所有帖子一样进行查询,其中开始的日期返回在时区中的一天的开始,而不是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 

ActiveSupport具有内置的方法来显示任何时区中的时间值。通常,您会将时区列添加到用户模型中,并将其设置为用户的首选区域

@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下的

ActiveSupport具有内置方法来显示任何时区中的时间值。通常,您会将时区列添加到用户模型中,并将其设置为用户的首选区域

@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下的