Set timezone for incoming xml data
I'm getting a datetime field from an API that does not explicitly set its timez开发者_StackOverflow社区one. When I place this into a database it's assuming the datetime must be in GMT, but the timezone is actually in Chicago time. (I say Chicago time, because I'm still unsure if this API factors in DST.) What is the best way for me to convert this time to GMT before adding it to the database?
Here is an XML sample of one of the nodes I'm referring to:
<FromDateTime>2011-03-17 08:00:00</FromDateTime>
In Ruby, I'm using this to add this record to the database.
:starttime => DateTime.parse(row.at_xpath("FromDateTime/text()").to_s),
I think what I need to do is add the difference in hours between CST and GMT to this last Ruby call, right? How would I do that?
Thanks!
Could you use Time instead? DateTime is not Daylight Savings Time aware. Time automatically sets to your local GMT offset for the given date/time and set DST if needed.
irb(main):014:0> require 'time'
irb(main):015:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011
irb(main):022:0> Time.parse('2011-03-17 08:00:00').dst?
=> true
Here is the case for standard time (I am in EST)
irb(main):025:0> Time.parse('2011-01-17 08:00:00')
=> Mon Jan 17 08:00:00 -0500 2011
irb(main):023:0> Time.parse('2011-01-17 08:00:00').dst?
=> false
If you are using ActiveSupport http://api.rubyonrails.org/classes/DateTime.html you can set to arbitrary time zone:
irb(main):039:0> Time.zone = 'America/Chicago'
=> "America/Chicago"
irb(main):040:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011
精彩评论