user984621
user984621

Reputation: 48443

Date/Time comparison 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 that start 60 minutes or less before day_start. With the following code, I get as a response "NO" instead of "YES".

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

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

Upvotes: 13

Views: 32665

Answers (4)

Darlan Dieterich
Darlan Dieterich

Reputation: 2537

Rememeber your result is false because the GMT, to resolve this and compare the only datetime without GMT using UTC, try this:

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

Upvotes: 0

Akhil Gautam
Akhil Gautam

Reputation: 169

Anywhere, if time A comes after time B, then A is considered to be greater than B. The same is 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 a timestamp before 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 NO is printed.

Upvotes: 0

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

Work them dates as UTC, so you will avoid time zone problems

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

Upvotes: 14

sawa
sawa

Reputation: 168081

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 Time objects, "follows" translates to "greater".

Upvotes: 2

Related Questions