【问题标题】:Ruby: Find the next timestampRuby:查找下一个时间戳
【发布时间】:2019-04-22 10:40:57
【问题描述】:

如果给我一个 HH:mm 格式的特定时间,例如:22:00,我如何获得可以安排此事件的下一个时间戳。

例如:

如果当前时间为22nd April 23:30,则应为23rd April 22:00(UTC格式可以,日期仅供参考)

如果当前时间是22nd April 18:00,它应该是22nd April 22:00

【问题讨论】:

    标签: ruby timestamp scheduling


    【解决方案1】:
    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 ...>
    

    【讨论】:

      【解决方案2】:

      您可以硬编码 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 和其他令人愉快的东西

      【讨论】:

        【解决方案3】:
        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 
        

        【讨论】:

          猜你喜欢
          • 2021-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-12
          • 2020-12-05
          • 2019-08-12
          • 1970-01-01
          相关资源
          最近更新 更多