【发布时间】: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