/ RAILS

Rails adds before? after? methods on date time classes

Rails Date, DateTime, Time, TimeWithZone class objects could be compared using less than, greater than signs. Rails added methods before? and after? to compare objects of these datetime classes.

ActiveSupport core extension calculation classes included a alias_method to < and > comparison functions which were already present.

alias_method :before?, :<
alias_method :before?, :<

Before this change

If we want to compare times, we had to use < and > operator as given below.

time_1 = Time.current - 2.hours
time_2 = Time.current

time_1 < time_1
# => true

After this change

If we want to compare times, we can use before? and after operator as given below.

Usage of before? for time comparison

time_1 = Time.current - 2.hours
time_2 = Time.current

time_1.before? time_1
# => true

Usage of after? for time comparison

time_1 = Time.current - 2.hours
time_2 = Time.current

time_1.after? time_1
# => false

These methods of time comparison are available on Date, Time, DateTime and TimeWithZone classes.

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee