Ruby:查找下一个时间戳

Ruby:查找下一个时间戳,ruby,timestamp,scheduling,Ruby,Timestamp,Scheduling,如果以HH:mm格式为我指定了一个特定的时间,如:22:00,那么当我可以安排此事件时,如何获取下一个时间戳 例如: event_time(15) # => 2019-04-23 15:00:00 +0300 event_time(22) # => 2019-04-22 22:00:00 +0300 如果当前时间为4月22日23:30,则应显示为4月23日22:00(UTC格式可以,日期仅供参考) 如果当前时间为4月22日18:00,则应显示为4月22日22:00要求“时间” re

如果以
HH:mm
格式为我指定了一个特定的时间,如:
22:00
,那么当我可以安排此事件时,如何获取下一个时间戳

例如:

event_time(15) # => 2019-04-23 15:00:00 +0300
event_time(22) # => 2019-04-22 22:00:00 +0300
如果当前时间为
4月22日23:30
,则应显示为
4月23日22:00
(UTC格式可以,日期仅供参考)

如果当前时间为4月22日18:00,则应显示为4月22日22:00

要求“时间”
require 'time'

✎ today_hour_x = DateTime.parse("22:00")
✎ today_hour_x + (today_hour_x - DateTime.now > 0 ? 0 : 1)
#⇒ #<DateTime: 2019-04-22T22:00:00+00:00 ...>
✎ today_hour_x = DateTime.parse("10:00")
✎ today_hour_x + (today_hour_x - DateTime.now > 0 ? 0 : 1)
#⇒ #<DateTime: 2019-04-23T10:00:00+00:00 ...>
✎ today\u hour\u x=DateTime.parse(“22:00”) ✎ today_hour_x+(today_hour_x-DateTime.now>0?0:1) #⇒ # ✎ today\u hour\u x=DateTime.parse(“10:00”) ✎ today_hour_x+(today_hour_x-DateTime.now>0?0:1) #⇒ #
您可以硬编码22,但作为更灵活方法的想法:

require 'date'

def event_time(hour)
  now = Time.now
  tomorrow = Date._parse((Date.today + 1).to_s)
  now.hour < hour ? Time.new(now.year, now.month, now.day, hour) : Time.new(tomorrow[:year], tomorrow[:mon], tomorrow[:mday], hour)
end
在Rails中,您还可以使用
Date.tomory
Time.now+1.day
和其他令人愉快的东西

require 'date'

def event_time(time_str)
  t = DateTime.strptime(time_str, "%H:%M").to_time
  t >= Time.now ? t : t + 24*60*60
end

Time.now
  #=> 2019-04-22 12:13:57 -0700 
event_time("22:00")
  #=> 2019-04-22 22:00:00 +0000 
event_time("10:31")
  #=> 2019-04-23 10:31:00 +0000