Ruby:
Comparing two dates

How to:

Ruby simplifies our lives with the Date class. Let’s see it in action.

require 'date'

date1 = Date.new(2023, 3, 14)
date2 = Date.new(2023, 3, 15)

puts date1 == date2   # Output: false
puts date1 != date2   # Output: true
puts date1 < date2    # Output: true
puts date1 > date2    # Output: false
puts date1 <= Date.today # Output: depends on today's date
puts date1 >= Date.today # Output: depends on today's date

Deep Dive

Date comparison isn’t new. It’s fundamental, like comparing integers, but trickier ‘cause dates have parts—days, months, years. In Ruby, the Date class (from the standard library) carries the weight, dealing with months, leap years, etc.

You’ve seen basic comparisons: ==, !=, <, >, <=, >=. But Ruby has more under the hood.

  • Date.parse can understand and convert string dates.
  • DateTime provides more precision, with time and timezone support.
  • Libraries like ‘ActiveSupport’ (from Rails) add even more date-related methods.

Watch out for pitfalls:

  • Timezones can trip you up if you’re not careful.
  • Leap seconds aren’t accounted for in Ruby’s standard Date/DateTime classes.

Alternatives to the Date class include:

  • Using timestamps and comparing them as numbers.
  • The ’time’ library for more advanced time handling.

Comparisons get complex quickly. What if you’re scheduling and need to compare date ranges, or handle recurring events? Higher-level abstractions built on Ruby’s Date and Time are often needed. ActiveRecord’s between? method or gems like ‘IceCube’ for recurring events can save tons of time and headaches.

See Also