导轨 - 当时间差超过18小时时,如何在导轨中存储时间

时间:2018-03-26 04:31:47

标签: ruby-on-rails ruby postgresql

我使用postgresql作为我的数据库。

目前我有时间模型,其中包含open_atclose_at字段。两个字段的数据类型都是时间。当我选择open_at时,时间是04:00,Rails默认将其存储为2000-01-01 04:00:00

# schema.rb

create_table "timings", force: :cascade do |t|
    t.string "day"
    t.time "open_at"
    t.time "close_at"
end

在我的情况下,商店的营业时间是08:00,关闭时间是02:00,所以当我存储该时间时,它将其存储为:

=> #<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 08:00:00", close_at: "2000-01-01 02:00:00", created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:34:16"> 

但是当我想获得正确的记录时,它没有响应有效记录。

上述时间记录的开放时间是早上8点,结束时间是凌晨2点。如果当前时间是早上6:46,我会进行以下查询:

2.4.2 :079 > Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
  Timing Load (0.7ms)  SELECT  "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:48:09.004429' and close_at > '2018-03-20 06:48:09.004496') LIMIT $1  [["LIMIT", 11]]
 => #<ActiveRecord::Relation []> 

...它应该返回结果,但结果是空的。当我将关闭时间更改为晚上11点(意味着23:00:00),并在查询下方运行时:

Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
  Timing Load (0.8ms)  SELECT  "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:49:12.307156' and close_at > '2018-03-20 06:49:12.307205') LIMIT $1  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 04:00:00", close_at: "2000-01-01 23:59:00", created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:49:07">]> 

......结果被重新调整。

有人可以解释一下如何为这种情况存储时间吗?或者我该如何解决这个时间问题?如果开启时间和收盘时间之间的差异超过18小时?或者我应该如何查询是否要获得正确的记录?

2 个答案:

答案 0 :(得分:0)

您应该以几秒或几分钟的时间将开始和结束时间存储为整数,因为将任意当前日期与存储的时间戳进行比较并不是您真正想要的。你不必说“比较现在的时间与这两个日期”,而是要说“将当天的开盘和收盘时间与当前时间进行比较。

然后你需要根据开启和关闭时间的值进行两次比较

# get your curent seconds after midnight
seconds = Time.current.to_i - Time.current.midnight.to_i

# compare this to the open and close times
Timing.where("(open_at < close_at and open_at < :seconds and close_at > :seconds) or (open_at > close_at and (open_at < :seconds or close_at > :seconds))", {seconds: seconds})

编辑:我的查询中存在一个微小但基本的错误,现在修复了。总是测试你的代码孩子!!

答案 1 :(得分:-1)

在解析时间信息时,如果不指定时区,永远不要这样做很重要。执行此操作的最佳方法是使用Time.zone.parse(将使用config.time_zone中指定的时区)而不仅仅使用Time.parse(将使用计算机的时区)。

您是否尝试过使用UTC? - 查看此link