We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
2023 / 09 / 24
TIL: Compare dates in Elixir
2023 / 09 / 24
The right way to do date comparison in Elixir
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