Skip to main content

Never compare dates in Elixir using "<" or ">"

·1 min

For the examples in this article I use the data structure Date. The same applies for DateTime or NaiveDateTime

Consider this:

early_june = ~D[2017-06-01]
late_june = ~D[2017-06-30]

How do you find out what’s earlier?

The naive approach is to use the comparison operator <:

early_june < late_june
# => true

That works. But this is tricky. It only works in some cases.

Now consider this:

late_june = ~D[2017-06-30]
early_july = ~D[2017-07-01]

What do you think the output is now?

late_june < early_july
# => false

Turns out: comparison with < (or >) just compares the struct fields (as the current version of the documentation states. My best guess is for same reason the day field has higher priority than the month field so this comparison fail sometimes.

To solve this use the compare function of the according modules:

Date.compare(late_june, early_july) == :lt
# => true