This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

Rails 6 adds before? and after? to Date , DateTime , Time and ActiveSupport::TimeWithZone classes.

before? and after? are aliases to < (less than) and > (greater than) methods respectively.

Let’s checkout how it works.

Rails 5.2

Let’s try calling before? on a date object in Rails 5.2.

>> Date.new(2019, 3, 31).before?(Date.new(2019, 4, 1))

=> NoMethodError: undefined method 'before?' for Sun, 31 Mar 2019:Date
	from (irb):1

>> Date.new(2019, 3, 31) < Date.new(2019, 4, 1)

=> true

Rails 6.0.0.beta2

Now, let’s compare Date , DateTime , Time and ActiveSupport::TimeWithZone objects using before? and after? in Rails 6.

>> Date.new(2019, 3, 31).before?(Date.new(2019, 4, 1))

=> true

>> Date.new(2019, 3, 31).after?(Date.new(2019, 4, 1))

=> false

>> DateTime.parse('2019-03-31').before?(DateTime.parse('2019-04-01'))

=> true

>> DateTime.parse('2019-03-31').after?(DateTime.parse('2019-04-01'))

=> false

>> Time.parse('2019-03-31').before?(Time.parse('2019-04-01'))

=> true

>> Time.parse('2019-03-31').after?(Time.parse('2019-04-01'))

=> false

>> ActiveSupport::TimeWithZone.new(Time.utc(2019, 3, 31, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).before?(ActiveSupport::TimeWithZone.new(Time.utc(2019, 4, 1, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]))

=> true

>> ActiveSupport::TimeWithZone.new(Time.utc(2019, 3, 31, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).after?(ActiveSupport::TimeWithZone.new(Time.utc(2019, 4, 1, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]))

=> false

Here is the relevant pull request for adding before? and after? methods and the pull request for moving before? and after? to DateAndTime::Calculations.