Comparing date and time in ruby

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 starting 60 minutes or less before day_start . With the following code, I get "NO" instead of "YES" as the response.

 if schedule.day_start < (Time.now + 60.minutes) "YES" else "NO" end 

Why is 2014-09-27 15:30:00 UTC greater than 2014-09-27 16:11:14 +0200 ?

+7
date comparison ruby ruby-on-rails time
source share
3 answers

Work with UTC dates to avoid problems with the time zone.

 if schedule.day_start.utc < (Time.now + 60.minutes).utc ... 
+9
source share

Because the

 2014-09-27 16:11:14 +0200 

at the same time with

 2014-09-27 14:11:14 UTC 

which precedes

 2014-09-27 15:30:00 UTC 

With Time objects, "follow" translates to "more."

0
source share

Anywhere, if time A comes after time B, then A is considered to be greater than B. The same thing in your case.


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.

Here you can clearly see that Time.now + 60.minutes is the timestamp before schedule.day_start. Thus, schedule.day_start is longer than Time.now + 60.minutes, so your "if" case is not executed and therefore NO .. p>

0
source share

All Articles