2
votes

I'm trying to parse a date and save it into a table. Here's the function:

defp string_to_datetime(string) do
  result = string
           |> String.split(";")
           |> List.last
           |> Timex.parse("{0M}/{0D}/{YYYY} {h12}:{m} {AM}")
  case result do
    {dt, _} -> dt
    :error -> nil
  end
end

The string needs some scrubbing at the start, but I get an error when I try to save it into this field:

field :first_appointment, Timex.Ecto.DateTime

Here's the error:

** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Timex.Protocol not implemented for :error
      (timex) lib/protocol.ex:1: Timex.Protocol.impl_for!/1
      (timex) lib/protocol.ex:36: Timex.Protocol.to_datetime/2

Really not sure what it means. Any ideas?

1

1 Answers

2
votes

Timex.parse/2 expects to return either {:ok, dt} or {:error, reason}

You have to change your case result like this:

case result do
  {:ok, dt} -> dt
  {:error, reason} -> IO.inspect reason
end

This is from Timex implementation:

@spec parse(String.t, String.t) :: {:ok, DateTime.t | NaiveDateTime.t} | {:error, term}