13

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?

4 Answers 4

14

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

if schedule.day_start.utc < (Time.now + 60.minutes).utc ... 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Benjamin for your message. I tried it, but Time.now.utc shows me 2014-09-27 14:10:14 UTC, but the current time is 2014-09-27 16:10:14 UTC. How to compare these two dates then? (schedule.day_start shows the "correct" date - not -2 hours)
In which context do you get Time.now? Because if for example it is assigned to a constant or a global variable it could have record the time when you started your server. Also check if you correctly set-up your config.time_zone, and off course if your system is on the right time with ntpdate
2

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".

2 Comments

Thank you Sawa for your message. But could you explain me, please, what do you mean by With Time objects, "follows" translates to "greater".?
If time A comes after (i.e. follows) time B on the temporal scale, then code A > B in Ruby would be true (i.e., A is greater than B).
0

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.

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.