Skip to content

Instantly share code, notes, and snippets.

@chanphiromsok
Last active February 10, 2022 05:54
Show Gist options
  • Save chanphiromsok/d892da9efa0588c457e40e711712edc8 to your computer and use it in GitHub Desktop.
Save chanphiromsok/d892da9efa0588c457e40e711712edc8 to your computer and use it in GitHub Desktop.
SortDateByEnum
Erlang/OTP 21 [erts-10.0.8] [source] [64-bit]
Interactive Elixir (1.10.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> dates = [~D[2018-01-31],~D[2019-02-01],~D[2020-03-01]]
[~D[2018-01-31], ~D[2019-02-01], ~D[2020-03-01]]
iex(2)> dates |> Enum.sort()
[~D[2019-02-01], ~D[2020-03-01], ~D[2018-01-31]]
iex(3)> dates |> Enum.sort(&(Date.compare(&1, &2) != :lt))
[~D[2020-03-01], ~D[2019-02-01], ~D[2018-01-31]]
iex(4)> dates |> Enum.sort(Date)
[~D[2018-01-31], ~D[2019-02-01], ~D[2020-03-01]]
iex(5)> dates |> Enum.sort({:desc, Date})
[~D[2020-03-01], ~D[2019-02-01], ~D[2018-01-31]]
iex(6)> dates |> Enum.sort({:asc, Date})
[~D[2018-01-31], ~D[2019-02-01], ~D[2020-03-01]]
# ref https://www.coletiv.com/blog/elixir-sort-lists-by-date/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment