Dates, date formatting, and parsing

Posted . Visible to the public.

There is no direct Elixir support for dates, though there is the Erlang calendar module Show archive.org snapshot . Dates, Times, and Date Times are represented as tuples

  • {2014, 2,10} - 10 Feb 2014
  • {16,45,15} - 16:45:15
  • {{2014,2,10}, {16,45,15}} - 10 Feb 2014, at 16:45:15

There are a number of in-progress date parsing and formatting libraries, eg:

I've chosen to just parse my own for the simple case, eg

def parse_date_time date_string do
    Regex.named_captures(%r/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})/g, date_string)
   |> values_to_integers
   |> date_time_captures_to_date_time
end

defp values_to_integers keyword_list do
  keyword_list
     |> Enum.map(fn {name, value} ->
     {name, safe_to_integer(value)}
   end)
 end

defp date_time_captures_to_date_time captures do
   {{captures[:year], captures[:month], captures[:day]}, {captures[:hour], captures[:minute], captures[:second]}}
end

The following produces a string such as "2010-02-10 13:05:07" from an Erlang date time.

def format_date_time({{year, month, day}, {hour, minute, second}}) do
   :io_lib.format("~4..0B-~2..0B-~2..0B ~2..0B:~2..0B:~2..0B",
     [year, month, day, hour, minute, second])
     |> List.flatten
     |> to_string
 end

Note that none of the above copes with bad input, so it's probably very naughty.

Paul Wilson
Last edit
Posted by Paul Wilson to elixir tips (2014-02-10 12:59)