David
David

Reputation: 957

Saving a Rails Record with a specific Timezone

How to save an event in Berlin with its own specific timezone and the next event in Tijuana with a different one?

The user is asked to choose a City for the event, as a source for e.g. +02:00.

I would like to receive a time code like this:

eventstart = "2011-07-22T18:00:00+02:00"

How would you go about creating that form?

UPDATE:

Realized saving as standard UTC is fine for many reasons. So now I am altering a time string in the view to present a *distance_to_time_in_words* for eventstart, depending on the user's local time.

Event in Tijuana, viewing from Berlin time:

old_zone = Time.zone
#=> "Berlin"
Time.zone = "Tijuana"
t = Time.zone.parse(eventstart.to_s[0..-7])
#=> 2011-07-22 18:00:00 +08:00
Time.zone = old_zone
#=> "Berlin"
distance_of_time_in_words(Time.now.in_time_zone, t)
#=> "9 hours"

cumbersome, but works for now. Improvement ideas welcome!

Upvotes: 4

Views: 2604

Answers (1)

naren
naren

Reputation: 937

Add a time_zone column to your database and use time_zone_select in your form to let user select the time_zone for which he is creating event.

And in the model you can convert the datetime to zone specific datetime and store utc in the database. You can use helper something like below

def local_time(date)
  Time.use_zone(self.time_zone) do
    Time.zone.at(date.to_i)
  end
end

Upvotes: 7

Related Questions