How do I have a fixed time in a fixed time zone in the ruby?

advertisements

I would like to create a Time/DateTime object that always represents "8am in New York", regardless of DST. How can i achieve this ?

One suggestion in the Rails documentation was to use

Time.zone = 'Eastern Time (US & Canada)'

in the following manner

around_filter :set_time_zone

def set_time_zone
  if logged_in?
    Time.use_zone(current_user.time_zone) { yield }
  else
    yield
  end
end

But i would like to avoid touching thread variables (which is what Time.use_zone is doing)


Try this:

ActiveSupport::TimeZone['Eastern Time (US & Canada)'].parse('8:00')

That will handle day light savings time issues

> eight_am = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].parse('8:00')
=> Fri, 22 May 2015 08:00:00 EDT -04:00

> eight_am.in_time_zone('America/Los_Angeles')
=> Fri, 22 May 2015 05:00:00 PDT -07:00