ruby 中的日期/时间比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26075078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date/Time comparison in ruby
提问by user984621
I have these dates and times:
我有这些日期和时间:
schedule.day_start # => 2014-09-27 15:30:00 UTC
date_now = Time.now # => 2014-09-27 15:11:14 +0200
date_now + 60.minutes # => 2014-09-27 16:11:14 +0200
I am trying to detect all schedules that start 60 minutes or less before day_start. With the following code, I get as a response "NO"instead of "YES".
我试图检测所有在 60 分钟或更短时间之前开始的计划day_start。使用以下代码,我得到的"NO"不是"YES".
if schedule.day_start < (Time.now + 60.minutes)
"YES"
else
"NO"
end
Why is 2014-09-27 15:30:00 UTCbigger than 2014-09-27 16:11:14 +0200?
为什么2014-09-27 15:30:00 UTC大于2014-09-27 16:11:14 +0200?
回答by Benj
Work them dates as UTC, so you will avoid time zone problems
将它们的日期设为 UTC,这样您就可以避免时区问题
if schedule.day_start.utc < (Time.now + 60.minutes).utc
...
回答by sawa
Because
因为
2014-09-27 16:11:14 +0200
is simultaneous to
与
2014-09-27 14:11:14 UTC
which comes before
在此之前
2014-09-27 15:30:00 UTC
With Timeobjects, "follows" translates to "greater".
对于Time对象,“跟随”翻译为“更大”。
回答by coderGuy
Anywhere, if time A comes after time B, then A is considered to be greater than B. The same is in your case.
在任何地方,如果时间 A 出现在时间 B 之后,则 A 被认为大于 B。您的情况也是如此。
schedule.day_start # => 2014-09-27 15:30:00 UTC
date_now + 60.minutes # => 2014-09-27 16:11:14 +0200 which is 2014-09-27 14:11:14 UTC.
schedule.day_start # => 2014-09-27 15:30:00 UTC
date_now + 60.minutes # => 2014-09-27 16:11:14 +0200 即 2014-09-27 14:11:14 UTC。
Here, you can clearly see that, Time.now + 60.minutes is a timestampbefore schedule.day_start. Thus, schedule.day_start is greater than Time.now + 60.minutes, that's why your "if"case doesn't hold true and hence NOis printed.
在这里,您可以清楚地看到,Time.now + 60.minutes 是schedule.day_start 之前的时间戳。因此,schedule.day_start 大于 Time.now + 60.minutes,这就是为什么您的“if”情况不成立,因此打印NO。
回答by Darlan Dieterich
Rememeber your result is falsebecause the GMT, to resolve this and compare the only datetime without GMT using UTC, try this:
请记住,您的结果是错误的,因为 GMT,要解决此问题并使用 UTC 比较没有 GMT 的唯一日期时间,请尝试以下操作:
minutes = 60.minutes
t1 = Time.at(schedule.day_start.utc).to_datetime
t2 = Time.at((Time.now + minutes).utc).to_datetime
if t1 < t2
"YES"
else
"NO"
end

