Skip to content

TIL: Compare dates in Elixir

Compare Elixir Date values by calendar order instead of Erlang term order.

1 min read

Use Date.compare/2 when ordering Elixir Date values. Operators such as < and > compare the underlying structs by Erlang term order, which is not guaranteed to match calendar order:

Elixir
~D[2025-12-31] < ~D[2026-01-01]
# false
Date.compare(~D[2025-12-31], ~D[2026-01-01])
# :lt

Date.compare/2 returns :lt, :eq, or :gt:

Elixir
today = Date.utc_today()
tomorrow = Date.add(today, 1)
yesterday = Date.add(today, -1)
Date.compare(today, tomorrow)
# :lt
Date.compare(today, today)
# :eq
Date.compare(today, yesterday)
# :gt

To test whether one date is earlier than or equal to another, match either :lt or :eq:

Elixir
Date.compare(today, tomorrow) in [:lt, :eq]
# true
Date.compare(today, yesterday) in [:lt, :eq]
# false

Reference

More posts connected by shared tags.