我正在尝试比较没有约会的时间,并发现它非常具有挑战性。基本上我正在记录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
答案 0 :(得分:2)
你想要的只是比较小时,所以停止比较整个时间并比较小时:
@rentalrequest.created_at.hour > 22
答案 1 :(得分:1)
找到晚上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小时窗口......前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