TL;DR - gist:5035116 · GitHub
I have a datetime picker in my app
(http://trentrichardson.com/examples/timepicker/). When someone clicks
in a text_field, the picker pops up and displays the calendar with the
time, and timezone.
I have the timezones for that select box populated like this
var timezones = function() {
zones = [
<% ActiveSupport::TimeZone.all.sort_by(&:name).each_with_index do
|timezone, index| %>
{ value: ‘<%= timezone.formatted_offset(false) %>’, label: “<%=
timezone.name %>” },
<% end %>
]
return zones;
};
The issue I’m running into is that when someone selects “Pacific Time
(US & Canada)” the value of that option is “-0800”. If the date they
selected is after March 10th (2013), then the “Pacific Time (US &
Canada)” time zone is actually “-0700”. So what happens is they save the
record as 2013-03-15 08:00 pm -0800, then it gets stored in the DB as
Fri, 15 Mar 2013 21:00:00 PDT -07:00.
Now, if they save the date as before March 10th (2013), then it saves
the correct time.
So, is there some method in rails where I can pass a date, and it will
return the proper offset for any time zone with DST into consideration?
Thanks,
~Jeremy
Ok, I think I’ve come up with 2 solutions.
-
Go with Javascript http://www.datejs.com/
Date.parse(“2013-03-09”).getUTCOffset() // “-0800”
Date.parse(“2013-03-10”).getUTCOffset() // “-0700”
-
Parse it in ruby
Time.parse(“2013-03-09 20:00:00”).localtime.strftime(“%z”) # “-0800”
Time.parse(“2013-03-10 20:00:00”).localtime.strftime(“%z”) # “-0700”
In case anyone else comes across this. I’m just praying this works
internationally O_o
Jeremy W. wrote in post #1099164:
The issue I’m running into is that when someone selects “Pacific Time
(US & Canada)” the value of that option is “-0800”. If the date they
selected is after March 10th (2013), then the “Pacific Time (US &
Canada)” time zone is actually “-0700”. So what happens is they save the
record as 2013-03-15 08:00 pm -0800, then it gets stored in the DB as
Fri, 15 Mar 2013 21:00:00 PDT -07:00.
I think that’s problem #1. In order to provide global timezone support
you should store all date/time values in UTC in the database and
translate the date/time into the local timezone of the server.
It is also often necessary to display dates and time in the local time
zone of the user, which means you’ll need to ask the user their time
zone and store that with the user.
Example:
2013-03-15 08:00 pm -0800 => 2013-03-15 16:00:00 UTC
Now timezone is no longer an issue… UTC is UTC everywhere, that’s the
point. If configured properly Rails should take care of this for your
automatically.
If you do need to display the time in the local time zone of the user
then you can.
utc_time.in_time_zone(“Pacific Time (US & Canada)”)
Note: in_time_zone is a Rails convenience.