Rails Time.zone processing not working as expected

I ran into this issue while testing a rails application deployed to two different staging servers in different time zones (PDT and CDT). Both servers have rails using UTC config.time_zone by default. Besides the time zone configuration is different, the clock is set on both servers.

Below I can see that in the rails console:

On the server where the system timezone is CDT,

Time.zone.parse("Mon May 28 2012 00:00:00 GMT-0700 (PDT)")
 => Mon, 28 May 2012 05:00:00 UTC +00:00 

      

On the server where the system timezone is PDT,

Time.zone.parse("Mon May 28 2012 00:00:00 GMT-0700 (PDT)")
 => Mon, 28 May 2012 07:00:00 UTC +00:00

      

A string Mon May 28 2012 00:00:00 GMT-0700 (PDT)

is an arbitrary date value sent by the client. This is a common scenario when using a javascript Date object coming in via the rails params collection.

Why are the two results Time.zone.parse(identical_date_time_string)

different?

If I run the following on both systems, the output is correct:

"Mon May 28 2012 00:00:00 GMT-0700 (PDT)".to_time
 => 2012-05-28 07:00:00 UTC

      

I am running rails 3.2.3 with ruby ​​1.9.3-p125, on ubuntu.

+3


source to share


2 answers


ActiveSupportTimeZone.parse

does not attempt to retrieve time zone information from the given string. It just extracts the date and time and converts it to TimeWithZone with the given (local) time zone.

str.to_time

will pay attention to the string "GMT-0700", but will produce a time without a time zone.



You can fake it out by extracting the "GMT ....." part and converting it to a UTC offset that is close, but not accurate, to the time zone.

0


source


This is how I do it



> Time.zone = "Hawaii"
=> "Hawaii"
> Time.zone.parse("Tue Mar 13 2012 13:00:00 GMT+1300 (NZDT)".sub("GMT",""))
=> Mon, 12 Mar 2012 14:00:00 HST -10:00
> Time.zone = "UTC"
=> "UTC"
> Time.zone.parse("Tue Mar 13 2012 13:00:00 GMT+1300 (NZDT)".sub("GMT",""))
=> Tue, 13 Mar 2012 00:00:00 UTC 00:00

      

0


source







All Articles