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
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]
If you need to parse date string into Date struct, you can use timex library:
iex> "01/01/2019" |> Timex.parse!("{D}/{0M}/{YYYY}") |> Timex.to_date()
{:ok, ~D[2019-01-01]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With