首页 > 解决方案 > 找出当前时间是否在两次之间

问题描述

我在 Postgresql 数据库中存储了两个时间列:open_timeclose_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 -0600open_time # => 2000-01-01 22:59:00 UTC.

我如何让它不包括日期,而只是比较时间?

标签: ruby-on-railsrubypostgresqldatetime

解决方案


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

推荐阅读