Ruby:查找下一个时间戳

时间:2019-04-22 10:40:57

标签: ruby timestamp scheduling

如果我以class A: def __init__(self, attrib): self.attrib = attrib def function(obj): obj.attrib = 8 obj = A(5) #This line prints 5 print(obj.attrib) #5 function(obj) #This line prints 8 print(obj.attrib) #8 格式指定了特定时间,例如:class A: def __init__(self, attrib): self.attrib = attrib def function(self, attrib): self.attrib = attrib obj = A(5) print(obj.attrib) #5 obj.function(8) print(obj.attrib) #8 ,那么当我可以安排此事件时,如何获得下一个时间戳。

例如:

如果当前时间为HH:mm,则应为22:00(UTC格式可以,日期仅供参考)

如果当前时间为22nd April 23:30,则应为23rd April 22:00

3 个答案:

答案 0 :(得分:0)

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 ...>

答案 1 :(得分:0)

您可以对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

我的当地时间现在是4月22日16:16。例如:

event_time(15) # => 2019-04-23 15:00:00 +0300
event_time(22) # => 2019-04-22 22:00:00 +0300

在Rails中,您还可以使用Date.tomorrowTime.now + 1.day和其他有趣的东西

答案 2 :(得分:0)

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 
相关问题