Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the zone offset for a time in Ruby on Rails?

I have a variable foo that contains a time, lets say 4pm today, but the zone offset is wrong, i.e. it is in the wrong time zone. How do I change the time zone?

When I print it I get

Fri Jun 26 07:00:00 UTC 2009 

So there is no offset, and I would like to set the offset to -4 or Eastern Standard Time.

I would expect to be able to just set the offset as a property of the Time object, but that doesn't seem to be available?

like image 960
Janak Avatar asked Jun 26 '09 12:06

Janak


People also ask

How do you offset time zones?

The zone offset can be Z for UTC or it can be a value "+" or "-" from UTC. For example, the value 08:00-08:00 represents 8:00 AM in a time zone 8 hours behind UTC, which is the equivalent of 16:00Z (8:00 plus eight hours). The value 08:00+08:00 represents the opposite increment, or midnight (08:00 minus eight hours).

Does timezone offset change?

An offset is the number of hours or minutes a certain time zone is ahead of or behind GMT**. A time zone's offset can change throughout the year because of Daylight Saving Time.

How do you write time with UTC offset?

The UTC offset is the difference in hours and minutes between Coordinated Universal Time (UTC) and local solar time, at a particular place. This difference is expressed with respect to UTC and is generally shown in the format ±[hh]:[mm], ±[hh][mm], or ±[hh].


1 Answers

You don't explicitly say how you get the actual variable but since you mention the Time class so I'll assume you got the time using that and I'll refer to that in my answer

The timezone is actually part of the Time class (in your case the timezone is shown as UTC). Time.now will return the offset from UTC as part of the Time.now response.

>> local = Time.now => 2012-08-13 08:36:50 +0000 >> local.hour => 8 >> local.min => 36 >>  


... in this case I happen to be in the same timezone as GMT

Converting between timezones

The easiest way that I've found is to change the offset using '+/-HH:MM' format to the getlocal method. Let's pretend I want to convert between the time in Dublin and the time in New York

?> dublin = Time.now => 2012-08-13 08:36:50 +0000 >> new_york = dublin + Time.zone_offset('EST') => 2012-08-13 08:36:50 +0000 >> dublin.hour => 8 >> new_york.hour => 3 

Assuming that 'EST' is the name of the Timezone for New York, as Dan points out sometimes 'EDT' is the correct TZ.

like image 183
Chris McCauley Avatar answered Oct 04 '22 11:10

Chris McCauley