Casting to DateTime from datetime_select submitted params

Hello,

The Phoenix datetime_select passes the input into params like this:

%{
  "day" => "7",
  "hour" => "0",
  "minute" => "10",
  "month" => "10",
  "year" => "2020"
}

How do I convert from this to an actual DateTime?

Another post in 2017 mentioned DateTime.cast() but that appears to no longer exist.

I tried DateTime.to_naive but that is throwing an error.

Hello!
Ecto.Type.cast/2 can be used for this

iex(10)> Ecto.Type.cast(:utc_datetime, %{
...(10)>   "day" => "7",
...(10)>   "hour" => "0",
...(10)>   "minute" => "10",
...(10)>   "month" => "10",
...(10)>   "year" => "2020"
...(20)> })
{:ok, ~U[2020-10-07 00:10:00Z]}
4 Likes

Thank you! You just saved me from hours of banging my head.