简体   繁体   中英

How do i get a fixed time in a fixed timezone in ruby?

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)

Well, you could approach the problem this way:

ny = Time.new(Time.now.year,Time.now.month,Time.now.day,8,0,0,"-05:00")

This will return an object ny that is set for 8:00 AM EST (New York) for the current day on any day that you execute it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM