开发者

Rails custom TimeZone

How can I set my rails application with custom timezone? I want to set my application timez开发者_开发百科one with UTC-04:00 without daylight saving.

update: To clarify my question, I understand that I can set the time zone name in the environment.rb file with one of the names from TimeZone constants. I want my application timezone as UTC -04:00 without daylight saving.

Thanks, Soe Moe


Suppose you want a timezone that does NOT use DST, and basically tracks Eastern Standard Time always (also known as Eastern Prevailing Time). You want it to be a -05:00 offset always.

Use the Timezone Etc/GMT+5. Rails will lazy-load timezones not in its normal list from TZInfo, so you can cherry pick from: http://tzinfo.rubyforge.org/svn/trunk/tzinfo/lib/tzinfo/definitions/Etc/

Here are some examples to prove this, in my Rails 3.2 rails console:

Daylight Savings example. October 4 is daylight savings time. You would expect your hours to be off by one for Eastern time and your special timezone. 2011-10-05 04:57:23 in UTC should be 2011-10-05 00:57:23 Eastern Daylight Time.

1.9.3p0 :014 > DateTime.civil(2011,10,5,4,57,23)
 => Wed, 05 Oct 2011 04:57:23 +0000 
1.9.3p0 :015 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Eastern Time (US & Canada)') 
 => Wed, 05 Oct 2011 00:57:23 EDT -04:00 
1.9.3p0 :016 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Etc/GMT+5')
 => Tue, 04 Oct 2011 23:57:23 GMT+5 -05:00 

Non-Daylight Savings example. December 1 is standard time. You would expect Eastern time and your custom "always EST" to be equivalent. 2011-12-01 02:30:45 should be 2011-11-30 21:30:45 in both EST and your special timezone.

1.9.3p0 :010 >   DateTime.civil(2011,12,1,2,30,45)
 => Thu, 01 Dec 2011 02:30:45 +0000 
1.9.3p0 :012 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Eastern Time (US & Canada)')
 => Wed, 30 Nov 2011 21:30:45 EST -05:00 
1.9.3p0 :013 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Etc/GMT+5')
 => Wed, 30 Nov 2011 21:30:45 GMT+5 -05:00 

Why is it GMT+5 and not GMT-5? I'm not entirely sure. I would have expected it to be GMT-5, but this is how the etc timezones seem to work in TZInfo.


Normally you'd only want to do this when the location you live in doesn't practice Daylight Savings Time. In your particular case, you're in luck, and can use the "La Paz" timezone. According to this website, it doesn't practice DST.

You can always run rake time:zones:all and see what UTC offsets correspond to the offset you're interested in using. Then google those offsets to see if they change during the year.

I don't know of a general method to tell Rails you want UTC +/- a fixed offset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜