TIL: Compare dates in Elixir

The right way to do date comparison in Elixir

2023-09-24
elixir

Directly comparing dates with >, <, <=, etc. won’t throw an error, but can give the wrong result.

The right way to go about it, is to use Date.compare/2.
E.g.:

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 check if a certain date is less-than or equal to another date, do:

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

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

References