Change Time Zone in Pure Ruby (Not Rails)

Change Time zone in pure ruby (not rails)

You can use the Time extensions from Active Support outside of Rails:

require 'active_support/core_ext/time'

t = Time.now
#=> 2014-08-15 15:38:56 +0200

t.in_time_zone('Pacific Time (US & Canada)')
#=> Fri, 15 Aug 2014 06:38:56 PDT -07:00

Now you can do

class Time
def to_pst
in_time_zone('Pacific Time (US & Canada)')
end
end

t = Time.now
#=> 2014-08-15 15:42:39 +0200

t.to_i
#=> 1408110159

t.to_pst
#=> Fri, 15 Aug 2014 06:42:39 PDT -07:00

t.to_pst.to_i
#=> 1408110159

# timestamp does not change!

Additionally you might also want the time extensions on Numeric and Date:

require 'active_support/core_ext/date'
require 'active_support/core_ext/numeric/time'

2.days.from_now
#=> 2014-08-17 15:42:39 +0200

Getting timezone in pure Ruby (no rails)

For the time being, this works TZ=Asia/Kolkata ruby -e "p Time.new(1942).strftime('%z')"

Setting the TZ environment variable also works from within Ruby: (seen in test_time_tz.rb)

def with_tz(tz)
old = ENV['TZ']
ENV['TZ'] = tz
yield
ensure
ENV['TZ'] = old
end

with_tz('Asia/Kolkata') do
(1935..1945).each do |x|
puts "#{x} => #{Time.local(x).strftime('%z')}"
end
end

Set time zone offset in Ruby

Change the time zone on your OS; Ruby will pick up the change.

Can I override the system timezone in Ruby?

You can also set environment variables from within ruby by accessing the ENV hash:

ENV['TZ'] = 'UTC'
Time.at 0
#=> 1970-01-01 00:00:00 +0000

also see this answer: Set time zone offset in Ruby, It provides a way to write something like

with_time_zone 'UTC' do
# do stuff
end

# now TZ is reset to system standard

Convert Time from one time zone to another in Rails

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)')

time_select with 12 hour time and Time Zone in Ruby on Rails

You can get time zone selects with the appropriate methods:

  • time_zone_options_for_select
  • time_zone_select

Similarly, there's date_select for dates.

Storage:

If the timezone is specific to the user and doesn't change, then store their time zone in their user record and set it when you load the current_user. Rails will convert times to/from UTC and always store UTC in the database and do the automatic convert to that default timezone for you (including daylight savings!). Easiest way to do it.

use_zone(zone) lets you override the default zone for a block, so you can accept a form value and set it with that function and set your value in that block.

UPDATE: I wrote up some Rails timezone examples as a blog entry.



Related Topics



Leave a reply



Submit