rails //白天按时区查询 [英] rails // query by timezone during daytime

查看:81
本文介绍了rails //白天按时区查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用时区时不太自信,在此方面寻求帮助

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

我有一项cron作业,可以不时地检查用户,这叫佣金任务。在此rake任务中,我查询用户并根据条件向每个用户发送电子邮件。

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

一个人将如何实现呢?

最佳

推荐答案

这取决于一些不同的东西,但是我将按以下方式我的网站已设置。我的用户模型有一个名为timezone的列,时区在该列中的存储方式示例为: US / Central

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"

我将通过放置

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

zones_map.values部分将拉回所有时区的列表,然后我们将它们映射为仅返回当前有一个小时的名称在8AM(8)和8PM(20)之间。然后,我们在查询中为用户使用map返回的数组。

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.

因此, z.now将提供该时区的当前时间,而我们使用(( 8..20).cover?以查看 z.now.hour是否介于8到20之间。

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.

** 12点以上的小时数不会重置为1 ,但继续为13、14等。

** 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.

这篇关于rails //白天按时区查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆