Elixir:
Comparing two dates

How to:

Elixir makes comparing dates straightforward. Here’s an example comparing today with tomorrow:

{:ok, today} = Date.new(2023, 4, 1)
{:ok, tomorrow} = Date.new(2023, 4, 2)

# Comparing if the same
Date.compare(today, today) # => :eq
# Output: :eq (equal)

# Which is earlier?
Date.compare(today, tomorrow) # => :lt
# Output: :lt (less than)

# Which is later?
Date.compare(tomorrow, today) # => :gt
# Output: :gt (greater than)

Deep Dive

Historically, date comparison wasn’t always a built-in feature in programming languages, and programmers would manually calculate the difference in seconds or days. Elixir’s standard library, however, includes the Date module with a compare/2 function that simplifies this task.

Alternatives for deeper time management exist within Elixir, like using the DateTime module for more precise time comparisons down to the second or microsecond.

When comparing dates, Elixir accounts for the complexities of the calendar system. It handles leap years, varying month lengths, and different calendar types, relying on the underlying Erlang :calendar module to ensure accuracy.

See Also