views:

35

answers:

1

I have a string like this:

"2010-01-01 12:30:00"

I need that to convert to UTC from the current local time zone.

I tried this, but it seems to think that the string is already UTC.

"2010-01-01 12:30:00".to_datetime.in_time_zone("Central Time (US & Canada)")
=> Fri, 01 Jan 2010 06:30:00 CST -06:00

I am not sure where to go from here.

added this from my comment:

>> Time.zone = "Pacific Time (US & Canada)"
=> "Pacific Time (US & Canada)"
>> Time.parse("2010-10-27 00:00:00").getutc
=> Wed Oct 27 06:00:00 UTC 2010
>> Time.zone = "Mountain Time (US & Canada)"
=> "Mountain Time (US & Canada)"
>> Time.parse("2010-10-27 00:00:00").getutc
=> Wed Oct 27 06:00:00 UTC 2010

Thanks for any help.

+2  A: 

Time.parse("2010-01-01 12:30:00").getutc

EDIT

(grinding teeth while thinking about the nightmare which is Ruby/Rails date/time handling)

OK, how about this:

Time.zone.parse("2010-01-01 12:30:00").utc

Note that Time.zone.parse returns a DateTime, while appending the .utc gives you a Time. There are differences, so beware.

Also, Time.zone is part of Rails (ActiveSupport), not Ruby. Just so you know.

zetetic
worked great! Thank you!
Toby Joiner
maybe I spoke too soon. It doesn't change the time based on the config.time_zone. I will add some code above for reference.
Toby Joiner
See my edit. (Extra characters added for SO to allow posting of this comment. Blah blah I am the walrus Etc and so on)
zetetic
that has to be the best comment I have read in a long time. It confused the crap out of me at first, but great now that I understand. Thank you for the answer, that worked. I am starting to feel the love with Rails dates/times...
Toby Joiner
What's wrong with the first version not using zone, I am completely confused?
Henrik
The first version works, but only for the current time zone (as defined by the operating system). The OP wants to let each request be in a different time zone, and for that we have to use the Rails TimeWithZone library, which is mixed into Ruby's Time library. Calling `Time.zone` sets the time zone for the operation to the one specified by setting `Time.zone = "some zone"`. `Time.zone.parse` builds a DateTime object in "some zone". `utc` converts the result to the UTC time zone. This allows the incoming web request to specify a local time, but store it as UTC in the database.
zetetic