Skip to content

Instantly share code, notes, and snippets.

@josevalim
Created January 21, 2015 11:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josevalim/1ed574b388c32f056da1 to your computer and use it in GitHub Desktop.
Save josevalim/1ed574b388c32f056da1 to your computer and use it in GitHub Desktop.
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