Comparing dates in Elixir
Notes
Elixir 1.15 introduced new DateTime and Date functions to compare dates.
Let’s cover the new functions, what already exists, and what to avoid at all costs!
DateTime.before?/2,DateTime.after?/2(and theirDatecounterparts) are new (since Elixir 1.15) and allow for strict comparison of datetimes (and dates),- We’ve had
DateTime.compare/2for a while, and it returns:gt,:lt, or:eq. The nice thing aboutcompare/2is that it has equality. - Never use
<,>,==to compare dates or datetimes! They perform structural comparisons. They don’t understand semantics. For more, take a look at the docs on structural comparison.