[Ruby on Rails (RoR)] Use #before? and #after? to compare Date, DateTime, Time or ActiveSupport::TimeWithZone in Rails 6

#before? and #after?

Date, DateTime, Time and ActiveSupport::TimeWithZone objects using before? and after? in Rails 6.

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

Date

1
2
3
4
5
6
7
> > 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

1
2
3
4
5
6
7
> > 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

1
2
3
4
5
6
7
> > 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

1
2
3
4
5
6
7
> > 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

References

[1] Rails 6 adds before? and after? to Date and Time | BigBinary Blog - https://bigbinary.com/blog/rails-6-adds-before-and-after-to-date-and-time

[2] ActiveSupport::TimeWithZone - https://api.rubyonrails.org/v6.1.0/classes/ActiveSupport/TimeWithZone.html

[3] Class: Date (Ruby 3.0.0) - https://ruby-doc.org/stdlib-3.0.0/libdoc/date/rdoc/Date.html

[4] Class: DateTime (Ruby 2.6.1) - https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/DateTime.html

[5] Class: Time (Ruby 3.0.0) - https://ruby-doc.org/core-3.0.0/Time.html