Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert local time to UTC in Rails

Tags:

In my MySQL database the updated_at field is being stored as UTC. Last week a record was entered at 7pm EDT and it's updated_at value is "2012-08-01 23:00:00". I'm trying to convert local time for a web client to UTC that can be compared against the updated_at field in the database.

As an example, I'd like to convert '08/01/2012 07:00 pm' to '2012-08-01 23:00:00' (accounting for me being in EDT) but I'm missing the time zone aspect to the conversion. '7:00 pm' is local time and could be from any time zone. My current code:

ruby-1.9.2-head :015 > from_date = DateTime.strptime('08/01/2012 07:00 pm', '%m/%d/%Y %H:%M %p') => Wed, 01 Aug 2012 19:00:00 +0000  ruby-1.9.2-head :016 > from_date = Time.zone.parse(from_date.to_s).utc => 2012-08-01 19:00:00 UTC 

Any thoughts?

Edit: Also, I could use "%Z" in my strptime call but that's assuming I have the timezone in the value, which I currently do not. I guess I could use Javascript to send that along with the date/time value.

like image 717
Chris Stewart Avatar asked Aug 06 '12 17:08

Chris Stewart


1 Answers

local to utc

created_at.utc

utc to local

created_at.localtime

like image 177
andyshi Avatar answered Oct 11 '22 00:10

andyshi