3

I am having an issue trying to deal with timezones in the JQuery date/time picker, with Rails. The datepicker, correctly shows the local timezone. The problem arises, when I save the selected date into my database, rails is saving it as a UTC time, even though the time is in the timezone of the client. When I attempt to convert the time to utc (Time.zone.parse(params[:time]).utc ), it gives me the same value as params[:time], which is the local time.

I do not want to change the Setting of config.time_zone in the environment.rb file, as I do not want the time to be saved in the local timezone of the server either.

What I want to do, is receive the local time, and convert it to utc, so I can schedule a cron job on a server whose time is set to utc. I would like to save the time in the database, as the users' local timezone... but I am unable to find a way to get the client's timezone!

Do I have any other options.. besides adding the timezone as an option on the datepicker?

user1160958
  • 193
  • 1
  • 4
  • 13

1 Answers1

2

DateTime Picker gives your views the correct time for the user - after that it is up to you to parse the time, adjust for the users' time zone, and schedule your cron job accordingly by adding or subtracting the appropriate amount of hours. Here's how I went about it:

# convert your param from a datepicker string to time:

start_time=DateTime.strptime(params[:start_time], "%m/%d/%Y %H:%M:%S").to_time

 # datepicker gives times in UTC to your server *BUT* it appears in the local time to the user. Make sure to adjust for this time difference.

start_time = start_time.in_time_zone(current_user.time_zone) # I let users pick their time zone.

 # account for DST. does this work? I think so.
 offset = (start_time.utc_offset)/60/60

 # now adjust by the hours offset.  you likely want to keep the time in utc for your database...

 adjusted_start_time = (start_time-offset.hours).utc

relavent info from another SO post Convert UTC to local time in Rails 3:

# Rails has it's own names. See them with: rake time:zones:us To see other zone-related rake tasks: rake -D time

# So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")
Community
  • 1
  • 1
Danny
  • 3,982
  • 1
  • 34
  • 42