0
votes

What is the best way to handle the following situation:

We have "admins" who create "events". These events can be nationwide, ie: different time zones. As of now there is a select menu with the current list of US time zones. There is a corresponding column in the database table, for the time zone selected. This is so the admin can select 5PM Eastern, 5PM Pacific, etc. Instead of trying to figure out the GMT equivalent.

The application is using UTC as per the environment.rb file, as the default time-zone.

If an admin selects "Eastern Time (US & Canada)", the date stamp selected is still saved as UTC (or the app default). I need to perform queries where events don't show up before the time selected above including the time zone.

Since the events need their own time zone, how should the data be saved? I was originally thinking I need to trick Rails before it saves the value, so it saves UTC offset for the time zone.

This would be handled in before_save and after_find model methods. But it doesn't seem to work, or rather I am missing something..

1

1 Answers

1
votes

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.