Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time.use_zone is not working as expected

So right now it is 2:54 PM PST in San Francisco. For some reason, this code block is not returning 12:54 PM HST in Hawaii. Am I missing something here? I would expect this code to return me the current time in Hawaii

Time.use_zone('Hawaii') do
  Time.now
end
# => 2012-01-03 14:54:54 -0800 
like image 663
denniss Avatar asked Jan 03 '12 22:01

denniss


3 Answers

This should work ok:

Time.use_zone('Hawaii') do
  p Time.zone.now
end
like image 174
Marek Příhoda Avatar answered Oct 10 '22 05:10

Marek Příhoda


Try using Time.now.in_time_zone inside your block instead.

> Time.use_zone('Hawaii') do
>   Time.now.in_time_zone
> end
 => Tue, 03 Jan 2012 13:07:06 HST -10:00 
like image 44
Dylan Markow Avatar answered Oct 10 '22 05:10

Dylan Markow


Use Time.current if you want now with timezone support. Time.now is dangerous when working in a timezone aware application, as a rule of thumb I never use Time.now, only Time.current. Rails time helpers like 2.hours.ago and 4.days.from_now are based off of Time.current as well.

Also, this is a great article with a great cheat sheet at the bottom: http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails

like image 30
Greg Olsen Avatar answered Oct 10 '22 04:10

Greg Olsen