在多区环境中工作时,最好将时区设置为 UTC。这在您的应用程序中完全有效。rb
Rails 会自动将所有时间转换为当前时区,可以使用
进行设置
Time.zone = "some-zone"
我使用的是 ApplicationController 中的 before_filter,我在其中根据当前用户设置时区。然后所有操作都在这个区域内工作,你不需要在你的控制器/模型/视图中考虑它。
假设您有一些带有日期时间字段的模型 Foo。然后在 irb 控制台中工作:
Time.zone = "Prague"
x = Foo.create(:it_will_happen_at => Time.zone.now)
x.it_will_happen_at # => Sat, 25 Sep 2010 13:45:46 CEST +02:00
Time.zone = "London"
# it is needed to refresh the field after a time zone has changed.
# In normal situation it'd not be needed, it's just for this console example
x.reload
x.it_will_happen_at # => Sat, 25 Sep 2010 12:44:46 BST +01:00
查看数据库时,您会发现该值为 Sat, 25 Sep 2010 11:45:46 UTC。
至于区域值,我更喜欢城市名称,因为它可以在夏令时(夏季/冬季)顺利运行。