ruby-on-rails - 查看当前时间是否在两个时间之间

标签 ruby-on-rails ruby postgresql date time

我在 Postgresql 数据库中存储了两个时间列:open_timeclose_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 -0600open_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/

相关文章:

ruby - 我试图理解 Ruby 中的 .freeze 概念。

Ruby 在扩展时调用模块方法

entity-framework - 在 Postgresql 中使用 Entity Framework 设计时

sql - 在 PostgreSQL 中计算移动天气统计数据

ruby-on-rails - rspec Rails 模拟 session 哈希

ruby-on-rails - Ruby 图形库

ruby-on-rails - 确保方程永远不会小于 0 - Ruby

php - 如何准备包含大量 if 语句的准备语句?

ruby-on-rails - 有什么方法可以暂时禁用 Heroku 托管的 Ruby on Rails 应用程序以停止每月付款?

ruby-on-rails - 如何在我的 Controller 规范中获取 view_context 以测试事件模型序列化程序