Compare two dates in string format "dd-mm-YYYY"

I have a date in string format like



Now i need to compare both the dates and check second date is greater than the first date. How can i achieve that.

Thank you.

Use Timex. It will let you parse then you can compare


Thank u for your response. Can u show me one example please. I have tried using Timex but couldn’t find proper solution.

  {:timex, "~> 3.7"}

a = Timex.parse!("02-02-2022", "{0D}-{0M}-{YYYY}")
b = Timex.parse!("31-01-2022", "{0D}-{0M}-{YYYY}")

IO.inspect(Date.diff(a, b))
IO.inspect(, b))

source: Date,, Timex


If you can use iso8601 date strings instead (yyyy-mm-dd), then you can use from_iso8601/2 Date — Elixir v1.13.2

Or very low level, if it’s really always in this format you can use String comparison with
String.split(“01-03-2022”, “-”) |> Enum.reverse() |> Enum.join() … should work or not?

You can also try datix. Datix uses the same format string as Calendar.strftime/3 and the package is a little bit smaller as timex.

iex(1)> Mix.install([{:datix, "~> 0.1"}])
Resolving Hex dependencies...
Dependency resolution completed:
  datix 0.1.1
* Getting datix (Hex package)
==> datix
Compiling 5 files (.ex)
Generated datix app
iex(2)> a = Datix.Date.parse!("02-02-2022", "%d-%m-%Y")
iex(3)> b = Datix.Date.parse!("31-01-2022", "%d-%m-%Y")
iex(4)> Date.diff(a, b)
iex(5)>, b)

Thank you very much for all your answers.

For future reference, please always post what have you tried.

1 Like