Skip to content

Instantly share code, notes, and snippets.

@b0oh b0oh/qwe.ex Secret
Last active Sep 15, 2015

Embed
What would you like to do?
defmodule Qwe do
@formats ["{ISO}", "{ISOz}", "{RFC822}", "{RFC822z}", "{RFC1123}", "{RFC1123z}",
"{RFC3339}", "{RFC3339z}", "{ANSIC}", "{UNIX}"]
def parse(nil), do: {:error, "Input string does not match format!"}
def parse(string) do
try do
acc = {:cont, {:error, "Input string does not match format!"}}
reduced = Enumerable.reduce(@formats, acc, fn f, acc ->
try do
case Timex.DateFormat.parse(string, f) do
{:ok, _} = ok -> {:suspend, ok}
{:error, _} -> {:cont, acc}
end
rescue
_ -> {:cont, acc}
end
end)
parsed = case reduced do
{_, parsed} -> parsed
{_, parsed, _} -> parsed
end
case parsed do
{:ok, date} ->
date = Timex.Date.universal(date) |> Timex.Date.Convert.to_erlang_datetime
{:ok, date}
{:error, _} = error ->
error
end
catch
_, {:error, _} = error ->
error
_, error ->
{:error, error}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.