Nick ONeill
Nick ONeill

Reputation: 7379

Get UTC timezone offset where hour is X in ruby

I have a cronjob running and every time the task is run I want to load contacts from my database where the local hour for that individual is the specified hour in my cron system.

For example: give me all contacts in the timezone where it is current the 4pm hour (16th hour).

In order to accomplish this, I want to make a simple function that returns the UTC timezone offset where the current hour is X.

This is the best solution I came up with but figure there's something more efficient.

def timezone_offset_for_hour hour
    ["-12:00","-11:00","-10:00", "-09:30","-09:00","-08:00","-07:00","-06:00","-05:00","-04:00","-03:30",
"-03:00","-02:00","-01:00","+00:00","+01:00","+02:00","+03:00","+03:30","+04:00","+04:30","+05:00","+05:30",
"+05:45","+06:00","+06:30","+07:00","+08:00","+08:30","+08:45","+09:00","+09:30","+10:00","+10:30",
"+11:00","+12:00","+12:45","+13:00","+14:00"].select{ |o| Time.now.getlocal(o).hour == hour }
end

The solution can be pure ruby or include Rails methods.

Upvotes: 0

Views: 319

Answers (1)

dimid
dimid

Reputation: 7631

If you need numerical offsets:

offsets = ActiveSupport::TimeZone.all.map{ |t| t.utc_offset / 3600.0 }.uniq

If you need the string representations:

offset_strs = ActiveSupport::TimeZone.all.map(&:formatted_offset).uniq 

Upvotes: 1

Related Questions