This blog is part of our Rails 6 series.
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.
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
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.

Written byAmit Choudhary
Related blogs
- 01Rails 6 adds support to persist timezones of Active JobSeptember 1, 2020 · Chetan Gawai
- 02Rails 6 adds including & excluding method on EnumerablesAugust 18, 2020 · Akhil Gautam
- 03Rails 6 fixes after_commit callback invocation bugFebruary 25, 2020 · Amit Choudhary
- 04Rails 6 adds rails db:prepare to migrate or setup a databaseDecember 10, 2019 · Akhil Gautam