Skip to content

TIL: Compare dates in Elixir

The right way to do date comparison in Elixir

1 min read

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.:

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

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

References

More notes connected by topic, not algorithmic noise.