Skip to content

Instantly share code, notes, and snippets.

@cooper6581
Created November 11, 2014 00:37
Show Gist options
  • Save cooper6581/8e7490d8804bceda38e7 to your computer and use it in GitHub Desktop.
Save cooper6581/8e7490d8804bceda38e7 to your computer and use it in GitHub Desktop.
Daily #188 - Easy
-module(easy).
-export([test/0]).
-import(lists, [reverse/1, filter/2, keyfind/3]).
-define(MONTHS, [{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"},
{"Apr", "04"}, {"May", "05"}, {"Jun", "06"},
{"Jul", "07"}, {"Aug", "08"}, {"Sep", "09"},
{"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}]).
get_url(Uri) ->
inets:start(),
ssl:start(),
{ok, {{_Version, 200, _Reason}, _Headers, Body}} = httpc:request(Uri),
string:tokens(Body,"\n").
convert_year(Year) ->
Year_int = list_to_integer(Year),
case Year_int >= 1950 of
true -> Year;
false ->
case Year_int >= 50 andalso Year_int =< 99 of
true -> "19" ++ Year;
false -> "20" ++ Year
end
end.
get_month(Month) ->
case keyfind(Month, 1, ?MONTHS) of
{_, Month_num} -> Month_num;
_ -> {error, Month}
end.
parse_dates(Dates) ->
parse_dates(Dates, []).
parse_dates([H|T], Acc) ->
parse_dates(T, [try_8601(H) | Acc]);
parse_dates([], Acc) ->
reverse(Acc).
try_8601(Date) ->
case re:run(Date, "^(\\d{4})-([01][0-9])-([0-3][0-9])$",
[{capture, all_but_first, list}]) of
{match, Result} ->
string:join(Result, "-");
_ ->
try_slash(Date)
end.
try_slash(Date) ->
case re:run(Date, "^([01][0-9])/([0-3][0-9])/(\\d{2})$",
[{capture, all_but_first, list}]) of
{match, [Month, Day, Year]} ->
string:join([convert_year(Year), Month, Day], "-");
_ ->
try_hash(Date)
end.
try_hash(Date) ->
case re:run(Date, "^([01][0-9])#(\\d{2})#([0-3][0-9])$",
[{capture, all_but_first, list}]) of
{match, [Month, Year, Day]} ->
string:join([convert_year(Year), Month, Day], "-");
_ ->
try_star(Date)
end.
try_star(Date) ->
case re:run(Date, "^([0-3][0-9])\\*([01][0-9])\\*(\\d{4})$",
[{capture, all_but_first, list}]) of
{match, [Day, Month, Year]} ->
string:join([Year, Month, Day], "-");
_ ->
try_month(Date)
end.
try_month(Date) ->
case re:run(Date, "^([JFMASOND][aepuco][nbrylgptvc]) ([0-3][0-9]), (\\d{2,4})$",
[{capture, all_but_first, list}]) of
{match, [Month, Day, Year]} ->
string:join([convert_year(Year), get_month(Month), Day], "-");
_ -> {error, Date}
end.
test() ->
Data = get_url("https://gist.githubusercontent.com/coderd00d/a88d4d2da014203898af/raw/73e9055107b5185468e2ec28b27e3b7b853312e9/gistfile1.txt"),
io:format("~p records read.~n", [length(Data)]),
Res = parse_dates(Data),
io:format("~p~n", [Res]),
io:format("Errors:~n~p~n", [filter(fun(E) -> is_tuple(E) end, Res)]),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment