马特非常明确的回答。您肯定希望将时间数据保存在 UTC TZ 中,然后将其转换为您的用户 TZ(或访客用户的服务器 TZ)
您正在使用全局设置为非 UTC TZ 的 MySQL,您可以使用以下查询覆盖此设置
SET time_zone = 'UTC';
问题是:此命令在 MySQL 中是会话范围的,每次初始化与数据库的新连接时都必须重新设置它。Rails ActiveRecord::ConnectionAdapters::ConnectionPool 类可以帮助你。请参阅此答案:如何在 Rails 中对数据库连接执行查询?
接下来,您需要在 application.rb 中设置您的服务器默认 TZ(您这样做了)并设置每个用户拥有自己的 TZ(您也这样做了)
最后,每次访问时间数据时都必须遵循 Rails 约定。我为您找到了这篇文章,其中包含非常有用的信息,它将回答您的所有问题: http ://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails
从那篇文章中摘录:
做事
2.hours.ago # => Fri, 02 Mar 2012 20:04:47 JST +09:00
1.day.from_now # => Fri, 03 Mar 2012 22:04:47 JST +09:00
Date.today.to_time_in_current_zone # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Date.current # => Fri, 02 Mar
Time.zone.parse("2012-03-02 16:05:37") # => Fri, 02 Mar 2012 16:05:37 JST +09:00
Time.zone.now # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Time.current # Same thing but shorter. (Thank you Lukas Sarnacki pointing this out.)
Time.zone.today # If you really can't have a Time or DateTime for some reason
Time.zone.now.utc.iso8601 # When supliyng an API (you can actually skip .zone here, but I find it better to always use it, than miss it when it's needed)
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z').in_time_zone(Time.zone) # If you can't use Time#parse
不要
Time.now # => Returns system time and ignores your configured time zone.
Time.parse("2012-03-02 16:05:37") # => Will assume time string given is in the system's time zone.
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z') # Same problem as with Time#parse.
Date.today # This could be yesterday or tomorrow depending on the machine's time zone.
Date.today.to_time # => # Still not the configured time zone.