Skip to content

Instantly share code, notes, and snippets.

@walter
Created August 30, 2017 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walter/a2321c8aa95a13fbd7280cfb8db271f6 to your computer and use it in GitHub Desktop.
Save walter/a2321c8aa95a13fbd7280cfb8db271f6 to your computer and use it in GitHub Desktop.
defmodule Junk.SensibleDateTimeType do
use Timex
require Logger
@behaviour Ecto.Type
def type, do: :naive_datetime
def load(%NaiveDateTime{} = value), do: value
def load(_), do: :error
def dump(%NaiveDateTime{} = naive_datetime) do
{:ok, naive_datetime}
end
def dump(_), do: :error
def cast(%NaiveDateTime{} = naive_datetime), do: naive_datetime
def cast(string) when is_binary(string) do
case Timex.parse(string, "{ISO:Extended}") do
{:ok, datetime} -> {:ok, Timex.to_naive_datetime(datetime)}
_ -> :error
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment