rails // query by timezone during daytime

烂漫一生 提交于 2020-01-02 05:26:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/36157457/rails-query-by-timezone-during-daytime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!