Rails - Date time select in specified time zone
Asked Answered
P

4

9

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.

Pontifical answered 6/6, 2011 at 1:4 Comment(0)
K
3

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.

Karinakarine answered 30/5, 2012 at 17:23 Comment(0)
O
1

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.

Overijssel answered 24/10, 2011 at 16:55 Comment(0)
G
0

How about something like this:

# change PST to correct zone abbrev.
new_zone = ActiveSupport::TimeZone.new("PST")
@performance.start_datetime = @performance.start_datetime.in_time_zone(new_zone)
Gemini answered 26/9, 2011 at 0:25 Comment(0)
P
0

I just noticed this is an old post but: If I were you, I would use a virtual attribute to represent the date time of the venue. For instance, you could add an attribute to performance called adjusted_start_time.

Pencil answered 29/1, 2012 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.