Skip to content

Instantly share code, notes, and snippets.

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
# Datetime itself should also be valid
def cast(%Ecto.DateTime{} = datetime) do
{:ok, datetime}
# 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}}
# 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.hour, dt.min, dt.sec}}}
def dump(_), do: :error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment