We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Sorting DateTime lists with Enum.sort/2
almirsarajcic
Enum.sort/1 puts January 31 after February 1:
dates = [~U[2026-02-01 09:00:00Z], ~U[2026-01-31 09:00:00Z], ~U[2025-12-15 09:00:00Z]]
Enum.sort(dates)
#=> [~U[2026-02-01 09:00:00Z], ~U[2025-12-15 09:00:00Z], ~U[2026-01-31 09:00:00Z]]
Enum.sort(dates, DateTime)
#=> [~U[2025-12-15 09:00:00Z], ~U[2026-01-31 09:00:00Z], ~U[2026-02-01 09:00:00Z]]
Without a sorter, Elixir compares DateTime structs as plain maps, field by field, and :day comes before :month and :year. That’s why the first result is ordered 1, 15, 31.
Passing the module makes Enum use DateTime.compare/2. The same works for Enum.max/2, Enum.min_by/3 and friends, and {:desc, DateTime} flips the order. Date, NaiveDateTime and Time have the same problem and the same fix.
Mind you, > and < compare the same way, and the compiler didn’t warn about a > b on two datetimes in Elixir 1.20.2. Use DateTime.after?/2 and DateTime.before?/2 for those checks.
copied to clipboard