20
votes

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.

2

2 Answers

38
votes

local to utc

created_at.utc

utc to local

created_at.localtime

1
votes

First I would check your time zone setting.

In your environment.rb (Rails 2) or application.rb (Rails 3) file, you can set the default timezone with: config.time_zone = 'Eastern Daylight Time (EDT)'

Secondly I would look at this post for information and guidance and tips to meet your needs:
http://databasically.com/2010/10/22/what-time-is-it-or-handling-timezones-in-rails/