How to Override the System Timezone in Ruby

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

Set time zone offset in Ruby

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

Ruby / Rails - Change the timezone of a Time, without changing the value

Sounds like you want something along the lines of

ActiveSupport::TimeZone.new('America/New_York').local_to_utc(t)

This says convert this local time (using the zone) to utc. If you have Time.zone set then you can of course to

Time.zone.local_to_utc(t)

This won't use the timezone attached to t - it assumes that it's local to the time zone you are converting from.

One edge case to guard against here is DST transitions: the local time you specify may not exist or may be ambiguous.

How to change default timezone for Active Record in Rails?

adding following to application.rb works

 config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local # Or :utc

How do I alter the timezone of a DateTime in Ruby?

Using Rails 3, you're looking for DateTime.change()

dt = DateTime.now
=> Mon, 20 Dec 2010 18:59:43 +0100
dt = dt.change(:offset => "+0000")
=> Mon, 20 Dec 2010 18:59:43 +0000

How to change the timezone of a TimeWithZone object?

You can change the default timezone for your rails application by changing config.time_zone in your environment.rb. Usually by default it is set to UTC.

In your case each coupon has its own timezone. So you have to use a different approach.
You don't have to change your save logic. You just need to change your retrieval
logic. Use the in_time_zone method of Time class.

c =  Coupon.last
p c.expired_at.in_time_zone(c.expired_at_timezone)
# => Tue, 09 Mar 2010 02:06:00 MST -07:00

Otherwise you can override the expired_at method of your Coupon model.

def expired_at
# access the current value of expired_at from attributes hash
attributes["expired_at"].in_time_zone(self.expired_at_timezone)
end

Now you can do the following:

p Coupon.last.expired_at
# => Tue, 09 Mar 2010 02:06:00 MST -07:00

How does Rails know my timezone?

From gettimeofday(), or so the ruby MRI source would have me believe:

int __cdecl
gettimeofday(struct timeval *tv, struct timezone *tz)
{
FILETIME ft;

GetSystemTimeAsFileTime(&ft);
filetime_to_timeval(&ft, tv);

return 0;
}

Per comment, this is a C function, called by the ruby date routines under the hood. You do not call the method yourself, rather you call the ruby methods you are calling.



Related Topics



Leave a reply



Submit