Rails daylight savings time not accounted for when using DateTime.strptime
date, ruby-on-rails-3, timezone
Solution
This is a frustrating problem. The Rails method you're looking for is `Time.zone.parse`. First use `DateTime.strptime` to parse the string, then run it through `Time.zone.parse` to set the zone. Check out the following console output:
> Time.zone
=> (GMT-06:00) Central Time (US & Canada)
> input_string = "10/12/12 00:00"
> input_format = "%m/%d/%y %H:%M"
> date_with_wrong_zone = DateTime.strptime(input_string, input_format)
=> Fri, 12 Oct 2012 00:00:00 +0000
> correct_date = Time.zone.parse(date_with_wrong_zone.strftime('%Y-%m-%d %H:%M:%S'))
=> Fri, 12 Oct 2012 00:00:00 CDT -05:00
Notice that even though `Time.zone`'s offset is -6 (CST), the end result's offset is -5 (CDT).
Problem
I've been working on parsing strings and I have a test case that has been causing problems for me. When parsing a date/time string with strptime, Daylight Savings Time is NOT accounted for. This is a bug as far as I can tell. I can't find any docs on this bug. Here is a test case in the Rails console. This is ruby 1.9.3-p215 and Rails 3.2.2. ``` 1.9.3-p125 :049 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z") => Sun, 15 Apr 2012 10:00:00 -0600 1.9.3-p125 :050 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z").utc => Sun, 15 Apr 2012 16:00:00 +0000 1.9.3-p125 :051 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z").utc.in_time_zone("Central Time (US & Canada)") => Sun, 15 Apr 2012 11:00:00 CDT -05:00 ``` As you can see, I have to convert to utc and then back to the timezone to get DST to be properly interpreted, but then the time is shifted one hour as well, so it's not what I parsed out of the string. Does someone have a workaround to this bug or a more robust way of parsing a date + time + timezone reliably into a DateTime object where daylight savings time is properly represented? Thank you. Edit: Ok, I found a workaround, although I'm not sure how robust it is. Here is an example: ``` ActiveSupport::TimeZone["Central Time (US & Canada)"].parse "2012-04-15 10:00" ``` This parses the date/time string into the correct timezone. I'm not sure how robust the parse method is for handling this so I'd like to see if there is a better workaround, but this is my method so far.