Search code examples
stringdatecastingelixir

Elixir, how to cast from string to Ecto.Date?


I have a date string with the format "dd/mm/yyyy" and I need to cast that value to Ecto.Date format.

I created a function like this, but I want to know if there is another way to do that.

defp format_birthday(birthday_string) do
  birthday = String.split(birthday_string, "/") |> Enum.reverse() |> Enum.join("-")

  Ecto.Date.cast(birthday)
end

Solution

  • If you don't want to have to depend on the Timex module:

    birthday = "01/12/2012"
    
    [dd, mm, yyyy] = String.split(birthday, "/")
    {:ok, date} = Date.from_iso8601("#{yyyy}-#{mm}-#{dd}")
    date
    
    ==> ~D[2012-12-01]