Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails // query by timezone during daytime

Not that confident when it comes to use timezones, looking for some help on this one

I have a cron job that check users every once in a while, which call a rake task. Within this rake task, I query users and sent each an email base on conditions.

I have the timezone info for each users. I'd like to have a query on those users that would only return the users that are currently in their daytime

How would one achieve that ?

Best

like image 211
Ben Avatar asked Oct 18 '22 13:10

Ben


1 Answers

This depends on a few different things, but I'll go by how my site is setup. My User model has a column named timezone, an example of the way timezones are stored in that column would be: "US/Central"

I would go about this by putting together an array of timezone names that are currently within a certain time range, then querying the User table.

zones = ActiveSupport::TimeZone.zones_map.values.
  map { |z| z.name if (8..20).cover?(z.now.hour) }.compact
users = User.where(timezone: zones)

The 'zones_map.values' part will pull back a list of all timezones, then we map them to only return the names of those that currently have an hour that is between 8AM (8) and 8PM (20). We then use the array returned by map within the query for users.

So 'z.now' will give us the current time in that timezone, and we use '(8..20).cover?' to see if 'z.now.hour' is between 8 and 20.

** Hours above 12 will not reset to 1, but instead continue as 13, 14, etc.

Not sure if there is a faster/more efficient way, but this is the way I have found for it to remain a query and avoid looping through all the users.

like image 166
MTarantini Avatar answered Nov 03 '22 06:11

MTarantini