dateelixirfile-listing

How do you get directory listing sorted by date in Elixir?


How do you get directory listing sorted by date in Elixir?

File.ls/1 gives list sorted by filename only.

No other functions in File module seem relevant for this.


Solution

  • Maybe there's a built-in function I don't know about, but you can make your own by using File.stat!/2:

    File.ls!("path/to/dir")
    |> Enum.map(&{&1, File.stat!(Path.join("path/to/dir", &1)).ctime})
    |> Enum.sort(fn {_, time1}, {_, time2} -> time1 <= time2 end)
    

    Example output:

    [
      {"test", {{2019, 3, 9}, {23, 55, 48}}},
      {"config", {{2019, 3, 9}, {23, 55, 48}}},
      {"README.md", {{2019, 3, 9}, {23, 55, 48}}},
      {"_build", {{2019, 3, 9}, {23, 59, 48}}},
      {"test.xml", {{2019, 3, 23}, {22, 1, 28}}},
      {"foo.ex", {{2019, 4, 20}, {4, 26, 5}}},
      {"foo", {{2019, 4, 21}, {3, 59, 29}}},
      {"mix.exs", {{2019, 7, 27}, {8, 45, 0}}},
      {"mix.lock", {{2019, 7, 27}, {8, 45, 7}}},
      {"deps", {{2019, 7, 27}, {8, 45, 7}}},
      {"lib", {{2019, 7, 27}, {9, 5, 36}}}
    ]