Rails jquery datepicker timezones

I have a problem with timezones in a JQuery date / time picker with Rails. Date sensor, shows the local time zone correctly. The problem occurs when I store the selected date in my database, rails store it as UTC time even though the time is in the client's timezone. When I try to convert time to utc (Time.zone.parse (params [: time]). Utc) it gives me the same value as params [: time] which is local time.

I don't want to change the config.time_zone setting in the environment.rb file as I don't want the time to be stored in the server's local timezone.

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

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

+3


source to share


1 answer


The DateTime Picker gives your views the correct time for the user - after that, you have to parse the time, adjust the users' timezone and schedule your cron job accordingly, adding or subtracting the appropriate number of hours.This is how I did 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 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)")

      

+2


source







All Articles