Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
defmodule Rocket.DateTime do
def type, do: :datetime
# Provide our own casting rules.
def cast(string) when is_binary(string) do
# Try to parse different formats here
end
# Datetime itself should also be valid
def cast(%Ecto.DateTime{} = datetime) do
{:ok, datetime}
end
# Everything else needs to be a failure though
def cast(_), do: :error
# Datetimes are never considered blank
def blank?(_), do: false
# When loading data from the database, we need to
# convert the Ecto type to our type:
def load({{year, month, day}, {hour, min, sec}}) do
{:ok, %Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec}}
end
# When dumping data to the database, we need to convert
# our type back to Ecto.DateTime one:
def dump(%Ecto.DateTime{} = dt) do
{:ok, {{dt.year, dt.month, dt.day}, {dt.hour, dt.min, dt.sec}}}
end
def dump(_), do: :error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment