Packages

TimeSeer is an Elixir library for parsing dates and times and returning Erlang style date and time tuples. Eg. "15:12:07" "2:42pm" "24/12/2014" will become {15,12,7}, {14,42,0}, and {2014,12,24} respectively.

Current section

Files

Jump to
time_seer lib time_seer.ex
Raw

lib/time_seer.ex

defmodule TimeSeer do
def date(string, :mmddyyyy) do
map = map_date(string)
{ to_int(map["third"]), to_int(map["first"]), to_int(map["second"]) }
end
def date(string, :ddmmyyyy) do
map = map_date(string)
{ to_int(map["third"]), to_int(map["second"]), to_int(map["first"]) }
end
def date(string, :yyyymmdd) do
map = map_date(string)
{ to_int(map["first"]), to_int(map["second"]), to_int(map["third"]) }
end
def date(string) do date(string, :yyyymmdd) end
def time(string) do
map = Regex.named_captures(~r/(?<first>[0-9]{1,2})[\:\.](?<second>[0-9]{1,2})[\:\.]?(?<third>[0-9]{1,2})?/, string)
hour = to_int(map["first"])
ampm = Regex.run(~r/[ap]m/i, string)
if ampm do hour = ampm_to_24_hour(hour, String.downcase(hd(ampm))) end
seconds = 0
if (map["third"]!="") do seconds = to_int(map["third"]) end
{ hour , to_int(map["second"]), seconds }
end
# If am: for the first hour at and after midnight subtract 12 hours so we get 0
def ampm_to_24_hour(hour, "am") when hour == 12 do hour - 12 end
def ampm_to_24_hour(hour, "pm") when hour < 12 do hour + 12 end
# default case: do not change the hour
def ampm_to_24_hour(hour, _) do hour end
def map_date(string) do
Regex.named_captures(~r/(?<first>[0-9]+)[^0-9]+(?<second>[0-9]+)[^0-9]+(?<third>[^\"]+)/, string)
end
def to_int(string) do
elem(Integer.parse(string),0)
end
end