Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime String to UTC in rails

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.

like image 287
Toby Joiner Avatar asked Oct 28 '10 19:10

Toby Joiner


2 Answers

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.

like image 152
zetetic Avatar answered Sep 28 '22 17:09

zetetic


In Rails 4 and above you can directly use in_time_zone

"2010-01-01 12:30:00".in_time_zone #=> Fri, 01 Jan 2010 12:30:00 EST -05:00  "2010-01-01 12:30:00".in_time_zone.utc #=> 2010-01-01 17:30:00 UTC 
like image 44
Deepak Mahakale Avatar answered Sep 28 '22 16:09

Deepak Mahakale