#How to do conditions/cases

5 messages · Page 1 of 1 (latest)

craggy harbor
#

I have an issue where I want to run a date string through a parser function.

Since my database holds data from third parties, the date strings come in many different formats so I have to run the string through several functions to return a proper datetime.

I'm trying to find an elegant way to do something like this (psuedocode):

my_date = cond {:ok, date} do
        Timex.parse(datestr, "{RFC1123}") -> date
        Timex.parse(datestr, "{RFC1123z}") -> date
        Timex.parse(datestr, "{RFC822}") -> date
        Timex.parse(datestr, "{RFC822z}") -> date
        ...more formats
end

do_something_with_date(my_date)

This sounds trivial but I'm pretty stumped honestly

native yarrow
#
with {:error, _} <- Timex.parse(datestr, "{RFC1123}"),
  {:error, _} <- Timex.parse(datestr, "{RFC1123z}"),
  {:error, _} <- ...
do
  {:error, :invalid_date}
else
  {:ok, date} -> do_something_with_date(date)
end
wooden lichen
#
formats = ~w[RFC1123 RFC1123z RFC822 RFC822z]

Enum.find_value(formats, fn format ->
  case Timex.parse(datestr, "{#{format}}") do
    {:ok, date} -> date
    {:error, _} -> nil
end)
craggy harbor
native yarrow
#

Yes because it doesn't match the error tuple