Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Time from one time zone to another in Rails

My created_at timestamps are stored in UTC:

>> Annotation.last.created_at => Sat, 29 Aug 2009 23:30:09 UTC +00:00 

How do I convert one of them to 'Eastern Time (US & Canada)' (taking into account daylight savings)? Something like:

Annotation.last.created_at.in_eastern_time 
like image 645
Tom Lehman Avatar asked Sep 06 '09 22:09

Tom Lehman


People also ask

How do you change timezone in Ruby?

You can do: Time. now + Time. zone_offset("PST") if you: require 'time' in your ruby script. guess, should have done that before commenting.

What is UTC time now in 24 hour format?

UTC time in ISO-8601 is 09:05:16Z. Note that the Z letter without a space.


1 Answers

Use the in_time_zone method of the DateTime class

Loading development environment (Rails 2.3.2) >> now = DateTime.now.utc => Sun, 06 Sep 2009 22:27:45 +0000 >> now.in_time_zone('Eastern Time (US & Canada)') => Sun, 06 Sep 2009 18:27:45 EDT -04:00 >> quit 

So for your particular example

Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)') 
like image 67
Steve Weet Avatar answered Oct 18 '22 10:10

Steve Weet