Time Formatting Parsing in Elixir

Our first example demonstrates time formatting and parsing in Elixir. Here’s the full source code:

defmodule TimeFormattingParsing do
  def run do
    # Here's a basic example of formatting a time
    # according to ISO8601, which is similar to RFC3339
    t = DateTime.utc_now()
    IO.puts DateTime.to_iso8601(t)

    # Time parsing uses the same format as formatting
    {:ok, t1} = DateTime.from_iso8601("2012-11-01T22:08:41+00:00")
    IO.inspect t1

    # Elixir uses strftime-like directives for custom formatting
    IO.puts Calendar.strftime(t, "%I:%M%p")
    IO.puts Calendar.strftime(t, "%a %b %d %H:%M:%S %Y")
    IO.puts Calendar.strftime(t, "%Y-%m-%dT%H:%M:%S.%f%:z")

    # For parsing custom formats, we use DateTime.from_iso8601/2
    {:ok, t2} = NaiveDateTime.from_iso8601("2014-10-23T20:41:00")
    IO.inspect t2

    # For purely numeric representations you can also
    # use standard string formatting with the extracted
    # components of the time value
    formatted = :io_lib.format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0B-00:00",
      [t.year, t.month, t.day, t.hour, t.minute, t.second])
    IO.puts formatted

    # DateTime.from_iso8601/2 will return an error on malformed input
    case DateTime.from_iso8601("8:41PM") do
      {:error, reason} -> IO.puts "Error: #{reason}"
      _ -> IO.puts "Parsed successfully"
    end
  end
end

TimeFormattingParsing.run()

Let’s break down the key points:

  1. Elixir uses DateTime and NaiveDateTime modules for working with dates and times.

  2. For ISO8601 formatting (similar to RFC3339), we use DateTime.to_iso8601/1.

  3. Parsing ISO8601 strings is done with DateTime.from_iso8601/1.

  4. Custom formatting is achieved using Calendar.strftime/2, which uses strftime-like directives.

  5. For parsing custom formats, you typically use NaiveDateTime.from_iso8601/1 or other specific parsing functions.

  6. Elixir doesn’t have a direct equivalent to Go’s layout-based parsing. Instead, it relies on specific parsing functions or third-party libraries for more complex parsing needs.

  7. For purely numeric formatting, you can use :io_lib.format/2 with the extracted date-time components.

  8. Error handling in parsing is typically done using pattern matching on the return tuple.

To run the program, save it as time_formatting_parsing.exs and use the elixir command:

$ elixir time_formatting_parsing.exs
2023-06-13T12:34:56.789012Z
#DateTime<2012-11-01 22:08:41Z>
12:34PM
Tue Jun 13 12:34:56 2023
2023-06-13T12:34:56.789012+00:00
~N[2014-10-23 20:41:00]
2023-06-13T12:34:56-00:00
Error: cannot parse "8:41PM" as ISO8601

This example demonstrates basic time formatting and parsing in Elixir. While the approach differs from other languages, Elixir provides powerful tools for working with dates and times.