0

处理以下情况的最佳方法是什么:

我们有创建“事件”的“管理员”。这些事件可以是全国性的,即:不同的时区。截至目前,有一个包含当前美国时区列表的选择菜单。数据库表中有一个对应的列,用于选择的时区。这样管理员就可以选择东部时间下午 5 点、太平洋时间下午 5 点等。而不是试图找出格林威治标准时间的等值。

该应用程序根据 environment.rb 文件使用 UTC 作为默认时区。

如果管理员选择“东部时间(美国和加拿大)”,则所选日期戳仍保存为 UTC(或应用默认值)。我需要在上面选择的时间(包括时区)之前未显示事件的情况下执行查询。

既然事件需要自己的时区,那么数据应该如何保存呢?我最初认为我需要在 Rails 保存值之前欺骗它,所以它保存了时区的 UTC 偏移量。

这将在 before_save 和 after_find 模型方法中处理。但它似乎不起作用,或者我错过了一些东西..

4

1 回答 1

1

You're missing a simple fact. Time is universal. 1:00pm in UTC is 1:00pm in UTC anywhere. You don't even need to store a time_zone with every event. You just need to let admins select it for easier time input. As far as backend, it's always in UTC. You can certainly input time from different timezone, and output into different timezone, but it's still the same "1:00pm in London" no matter how you twist it. So when a user is looking at events, you can simply do event_date < Time.now.utc (all past events).

However, if the observing user is actually in a different timezone from the events, and you want to display event dates in the user's home timezone, then you can let user select their home timezone, and store it in users table. Then in before_filter on your ApplicationController you can just do:

class ApplicationController < ActionController::Base
  before_filter :set_time_zone

  private
  def set_time_zone
    Time.zone = current_user.time_zone if current_user
  end
end

Then every Time value that comes from database (such as event.date) will be automatically converted in the user's home time zone.

Or maybe I misunderstood the question. : ) Let me know.

于 2010-07-09T05:28:22.707 回答