Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 873
Hatsumi Avatar asked Jun 08 '26 06:06

Hatsumi


2 Answers

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]
like image 170
7stud Avatar answered Jun 10 '26 06:06

7stud


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]}
like image 35
apelsinka223 Avatar answered Jun 10 '26 06:06

apelsinka223



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!