Converting date string to Ecto.Date

Hey guys.

I’m new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for example “22.02.2017” (dd.mm.yyyy) to Ecto.Date struct. How can I do that? Or at least to a “yyyy-mm-dd” string
I come from PHPs background and PHP has strtotime() function, which converts any date format you can throw at it into timestamp… Is there anything like that in elixir / phoenix?

Thanks

1 Like

You can use Ecto.Date.cast. See https://hexdocs.pm/ecto/Ecto.Date.html for reference.

1 Like

But how can I turn that dd.mm.yyyy date to yyyy-mm-dd? What is the best practice? Cast the string into tuple?

1 Like

You can convert by using String.replace("22.02.2017", ~r/\./, "-") and then cast it to Ecto.Date

2 Likes

You can also use Elixir’s Date module:

iex(11)> Date.from_iso8601!("2017-02-22")
~D[2017-02-22]

I believe Ecto.Date and DateTime are deprecated as of Ecto 2.1.

9 Likes