我在 Postgresql 数据库中存储了两个时间列:open_time
和 close_time
。我试图找出当前时间(忽略日期)是否在两个时间之间,忽略日期。
此代码比较日期和时间:
current_time = Time.now
if current_time.between?(store.open_time, store.close_time)
puts "IN BETWEEN"
end
它不起作用,例如,当 current_time # => 2018-06-06 23:59:49 -0600
和 open_time # => 2000-01-01 22 :59:00 UTC
.
如何让它不包括日期,而只比较时间?
最佳答案
require 'time'
TIME_FMT = "%H%M%S"
def store_open_now?(open_time, close_time)
nt = Time.now.strftime(TIME_FMT)
ot = open_time.strftime(TIME_FMT)
ct = close_time.strftime(TIME_FMT)
ot <= ct ? (nt >= ot && nt <= ct) : (nt >= ot || nt <= ct)
end
在我撰写本文时,时间现在大约是午夜过后 32 分钟。
Time.now.strftime(TIME_FMT)
#=> "003252"
假设
open_time = DateTime.parse("09:00")
#=> #<DateTime: 2018-06-07T09:00:00+00:00 ((2458277j,32400s,0n),
# +0s,2299161j)>
close_time = DateTime.parse("17:00")
#=> #<DateTime: 2018-06-07T17:00:00+00:00 ((2458277j,61200s,0n),
# +0s,2299161j)>
然后
open_time.strftime(TIME_FMT)
#=> "090000"
close_time.strftime(TIME_FMT)
#=> "170000"
store_open_now?(open_time, close_time)
#=> false
现在假设开门时间相同,但关门时间晚一些。
close_time = DateTime.parse("01:00")
#=> #<DateTime: 2018-06-07T01:00:00+00:00 ((2458277j,3600s,0n),
# +0s,2299161j)>
然后
close_time.strftime(TIME_FMT)
#=> "010000"
store_open_now?(open_time, close_time)
#=> true
关于ruby-on-rails - 查看当前时间是否在两个时间之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733988/