I collect data from a user for the delivery date and time and timezone.
I want to convert the time and date to the time in the timezone of the user and then save this to the database.
I do the following on the update:
Model.rb before_update :convert_to_timezone def convert_to_timezone #convert the time to UTC time Time.zone = self.time_zone #set the time zone to that of the user self.deliver_on = Time.zone.parse(self.deliver_on.to_s) #get the correct time for this time zone Time.zone = Rails.configuration.time_zone #set the time zone back to the default timezone end
When I look in the database I expect to see the time converted to the time and date of my application.
Time: '6:00' Timezone: 'Hawaii' Date: August 16, 2011
self.deliver_on = 2011-08-15 22:00:00 -1000
This is exactly what is required as Hawaii is on the other side of the International Date line so the date is correct as well.
The problem is when I look in the database this is not being saved.
How can I save this to the database? Update
I figured it out. The time coming from the form was already stamped as being UTC so when I tried to set the time to the UTC code for the timezone the user selected on the form it was actually converting the time to the time in that zone.
SO I did the following:
def convert_to_timezone Time.zone = self.time_zone local_time = Time.zone.parse(self.deliver_on.to_s.chomp('UTC')) self.deliver_on = local_time.in_time_zone(Rails.configuration.time_zone) Time.zone = Rails.configuration.time_zone end
Not sure if its the right way but it works like a charm.