我正在使用 Rail 5.2 应用程序处理
Location
记录和关联的 OpeningHour
记录。 OpeningHour
模型包含字段 day
(枚举)、starts_at
(时间)和 ends_at
(时间)。
当我运行下面的代码时,Rails 将
Time.now
从本地时区 (+08:00) 转换为 UTC 时间,然后将时间与任何 OpeningHour
记录的时间进行比较。由于 starts_at
和 ends_at
字段存储为没有时区的时间,因此查询中使用的时区不会对齐。
Location.opening_hours.where("start_at <= ? AND ends_at >= ?", Time.now, Time.now).any?
告诉 Rails 在比较之前不要转换为 UTC 时间的最佳方法是什么,因为数据库中的时间已经在
localtime
中?
任何帮助将不胜感激!
如果您在 application.rb 中将本地时区配置为
config.time_zone = "My TimeZone"
那么您可以使用 Time.zone.now
来获取本地时区的时间:
Location.opening_hours.where("start_at <= ? AND ends_at >= ?", Time.zone.now, Time.zone.now).any?
也遇到了这个问题,我正在使用从时间对象中剥离时区信息的解决方法,以强制 Rails 停止将时间转换为 UTC:
Location.opening_hours.where("start_at <= ? AND ends_at >= ?", Time.now.strftime("%H:%M:%S"), Time.now.strftime("%H:%M:%S")).any?