jackerman09
jackerman09

Reputation: 2658

Comparing times in a rails model validation is not working

I am trying to have my validation prevent a user from creating an Appointment that is not in the future. My validation is working to prevent past appointments from being created, but it is also preventing the user from creating appointments today, which should be allowed. What is wrong here?

Appointment.rb:

validates :pickuptime, presence: true
validate  :pickuptime_is_in_future

byebug
def pickuptime_is_in_future
  if pickuptime < Time.now
    errors.add(:pickuptime, "Appointment must be in the future")
  end
end

I debugged this (using byebug), and at the point where the byebug line is, I found the following:

(byebug) Time.now
2014-12-20 20:33:35 -0500

(byebug) pickuptime
Sat, 20 Dec 2014 21:34:00 UTC +00:00

(byebug) pickuptime < Time.now
true

Why is this true if Time.now is 8:33pm and pickuptime is 9:34 pm?

Any help would be much appreciated, thanks!

Upvotes: 1

Views: 171

Answers (1)

Chris Scott
Chris Scott

Reputation: 78

TlDR;

Your Time Zone is not set.

A list of all available Time Zones can be fetched using

rake time:zones:all

and Set your timezone.

# application.rb:
class Application < Rails::Application
 config.time_zone = 'Eastern Time (US & Canada)'
end

Long Answer

You are seeing a difference because of Time Zones and your local system UTC Offset.

(byebug) Time.now
2014-12-20 20:33:35 -0500

This Time is -05:00 hours or 5 hours behind UTC

(byebug) pickuptime
Sat, 20 Dec 2014 21:34:00 UTC +00:00

This Time is 00:00 hours or 0 hours behind UTC

 (byebug) pickuptime < Time.now
 true

Therefore this is true because your local time is actually

Sun, 21 Dec 2014 01:33:35 UTC +00:00

and the pickuptime is

Sat, 20 Dec 2014 21:34:00 UTC +00:00

and happens because your Time Zone is not set. To do so follow below.

A list of all available Time Zones can be fetched using

rake time:zones:all

and set your timezone. As detailed in ActiveSupport::TimeZone

# application.rb:
class Application < Rails::Application
 config.time_zone = 'Eastern Time (US & Canada)'
end

Upvotes: 2

Related Questions