-
-
Save b0oh/48b160f5a51cb612ec3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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