ruby-on-rails - 找出当前时间是否在两次之间
问题描述
我在 Postgresql 数据库中存储了两个时间列:open_time
和close_time
. 我试图找出忽略日期的当前时间是否在两次之间,忽略日期。
此代码比较日期和时间:
current_time = Time.now
if current_time.between?(store.open_time, store.close_time)
puts "IN BETWEEN"
end
它不起作用,例如 whencurrent_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
推荐阅读
- c++ - WM_PAINT 基于按钮点击
- c# - Unity C# Input.GetMouseDown(1) 在更新函数中只发生一次
- gentoo - Gentoo 在一个命令中安装多个包
- vba - 为什么 VBA 在指定文件夹中找不到文件
- angular - 合并不同的数据以响应 2-request
- android - Flutter - flutter_blue 库连接问题
- javascript - 从现在到一天结束的所有时间
- ios - 无法在按钮和 UIView 周围创建阴影
- python - RabbitMQ中的回调函数,鼠兔basic_consume是否以阻塞方式(一一)执行?
- r - 保持 ggplot 次轴比例固定