Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Date time select in specified time zone

I'm working with an app for a concert tour website, where all times (announcement times, on-sale start times, and event start times) are local to each particular venue's time zone. I take the user entered date/time where applicable and run a before_filter to set the appropriate time zone so that everything is stored in the database in UTC. For the 'new' form and for displaying the times in index and show actions, no problem at all. When the data is brought back out of the database and into a view, I use in_time_zone to adjust per the particular venue.

The only issue is on the edit form. The date/time select is showing the data in UTC. When I'm working on the site, I mentally adjust, but for others it's confusing. I'd like to do something along the lines of:

<%= f.datetime_select :start_datetime.in_time_zone(@event.time_zone) %>

Or, in the controller:

def edit
  @performance = Performance.find(params[:id])
  @event = @performance.event
  @performance.start_datetime = @performance.start_datetime.in_time_zone(@event.time_zone)
end

Then simply, <%= f.datetime_select :start_datetime %>.

Unfortunately, I haven't found the right way to do this. Do you have any ideas worth giving a shot?

Thank you very much.

like image 739
John Harper Avatar asked Jun 06 '11 01:06

John Harper


2 Answers

You may use default method of datetime_select, as following:

%br
= f.label :req_sess_start, "Session starts at"
= f.datetime_select(:req_sess_start, :start_year => 2010, :ampm => true, :default => 0.days.from_now.in_time_zone(@timezone))

Because of the default value shown, client will assume that times has to be entered in his/her local timezone, but... this value will be actually in the timezone default to your application (as provided in application.rb, and the default is UTC). So, you would require some server side coding to convert it to correct value.

like image 180
Munish Avatar answered Sep 17 '22 19:09

Munish


I'm not sure if I understand what you want to do, but since you're storing the @event.time_zone, you could add

:default => start_time.in_time_zone(@event.time_zone)

to your datetime_select form field.

like image 24
rapcal Avatar answered Sep 18 '22 19:09

rapcal