【问题标题】:Ruby - is 2am on any date later than 10pm on any date (TRUE)Ruby - 任何日期的凌晨 2 点,晚于任何日期的晚上 10 点(真)
【发布时间】:2014-10-22 21:51:44
【问题描述】:

我正在尝试比较没有日期的时间,发现它非常具有挑战性。基本上我正在记录created_at 并试图说,无论日期如何,它是否晚于晚上 10 点?如果是这样,请采取某些措施。

注意:时间以UTC格式存储在我的数据库中,我只关心太平洋,所以我首先检索的任何时间都必须转换为太平洋。

例子:

#1) User makes a request at 2am Pacific Time on 10/10/14, this is the result:
  @rentalrequest.created_at => Wed, 22 Oct 2014 10:03:48 UTC +00:00 
  @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)") => Wed, 22 Oct 2014 03:03:48 PDT -07:00 

# Code evaluates whether or not the Pacific Time of creation was later than 10pm. This is where I struggle, so I put the failed options below

#2a) Compare time to a Time object set to 10pm: DOESN'T WORK BECAUSE TIME PARSE ADDS TODAY'S DATE, EVEN THOUGH THE RIGHT COMPARISON WOULD HAVE BEEN TO COMPARE TO 10pm THE DAY BEFORE
  @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)").strftime('%H:%M:%S') > Time.parse("22:00:00") => false, since Time.parse("22:00:00") evaluates to => 2014-10-22 22:00:00 -0700 

#2b) Compare only times by using strftime: DOESN'T WORK BECAUSE NOW IT'S A STRING COMPARISON
  @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)").strftime('%H:%M:%S') > "22:00:00" => false 

#2c) Compare strftimes that are converted again to time variables: DOESN'T WORK FOR SAME REASON AS 2a
  @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)").strftime('%H:%M:%S').to_time > Time.parse("22:00:00").strftime('%H:%M:%S').to_time => false

【问题讨论】:

    标签: ruby datetime ruby-on-rails-4 time


    【解决方案1】:

    你只想比较小时,所以停止比较整个时间并比较小时:

    @rentalrequest.created_at.hour > 22
    

    【讨论】:

    • 实际上这不起作用,因为第一部分将返回不大于 22 的 2。但这让我意识到我可以做到 @rentalrequest.created_at.hour < 8 || @rentalrequest.created_at.hour > 22 谢谢!
    • @james 它将返回一个介于 0 和 23 之间的数字。如果你在晚上 10 点之后,你想要22。
    【解决方案2】:

    这会找到晚上 10 点到午夜之间的时间

    @time = @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)")
    @time < @time.end_of_day and @time > (@time.end_of_day - 2.hours)
    

    回答

    这需要您四个小时。并比较下午 6 点和晚上 10 点之间的 4 小时窗口......向前四个小时是晚上 10 点和凌晨 2 点。你可以做两个小时作为替代。只要知道end_of_day 是午夜前 1 秒。

    @time = @rentalrequest.created_at.in_time_zone("Pacific Time (US & Canada)")
    @four_earlier = @time - 4.hours - 1.second
    if @four_earlier < (@four_earlier.end_of_day - 2.hours) and @four_earlier > (@four_earlier.end_of_day - 6.hours)
      # do something
    end
    

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多