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

I have a date in string format like

“31-01-2022”

“02-02-2022”

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

2 Likes

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

Mix.install([
  {: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(Date.compare(a, b))

source: Date, Date.compare/2, Timex

3 Likes

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:
New:
  datix 0.1.1
* Getting datix (Hex package)
==> datix
Compiling 5 files (.ex)
Generated datix app
:ok
iex(2)> a = Datix.Date.parse!("02-02-2022", "%d-%m-%Y")
~D[2022-02-02]
iex(3)> b = Datix.Date.parse!("31-01-2022", "%d-%m-%Y")
~D[2022-01-31]
iex(4)> Date.diff(a, b)
2
iex(5)> Date.compare(a, b)
:gt
3 Likes

Thank you very much for all your answers.

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

1 Like