I have a rails app where the time zone is being set in application.rb:
config.time_zone = 'Pacific Time (US & Canada)'
I want to access this time zone in a controller so that I can convert a UTC time to local time. I have tried numerous things like the following:
@event.start_time = Time.zone.utc_to_local(@event.start_time)
But it doesn’t seem to allow me to call methods on Time.zone. I also tried it using ActionHelper::Time but did not seem to do it. How are these methods accessed from the controllers?
EDIT: I think part of the problem is I was trying to reset @event.start_time. I changed it so that it’s
@event = current_user.events.build(params[:event])
date = Date.parse(params[:event]["start_date"])
utc_start_time = DateTime.civil( date.year.to_i,
date.month.to_i,
date.day.to_i,
params[:event]["start_hour_min(4i)"].to_i,
params[:event]["start_hour_min(5i)"].to_i )
@event.start_time = Time.zone.utc_to_local(utc_start_time)
@event.save
This now saves but only sometimes (havent yet figured out what factors determine it) and is offsetting in the wrong direction. I will edit this as I’m able diagnose whats happening further.
The way Time Zones work is the all times are stored in the DB as UTC. If your times are not in UTC then you will need to convert them in the DB. Then once you set the time zone in config Rails will translate all times to the config’d time automatically. In the example you gave Rails through active record will display:
You can use this to support time zones based on the user, for example you could setup something like the filter below.
There is a good screen cast on how time zone support works, you can watch it here.