Elixir – Simple Current Time Helper Module

As it was a little less then trivial to get the current system time as string in Elixir, I’ve added this helper module that basically converts Erlang’s calendar output to a string that can be flexibly formatted:

defmodule Util.Time do
  @moduledoc """
  Time helper functions.
  """

  @doc """
  Get current time as string using Erlang's calendar module.
  """
  @spec now_to_string() :: String.t
  def now_to_string() do
    {{year, month, day}, {hour, minute, second}} = :calendar.local_time()
    "#{day}.#{month |> zero_pad}.#{year} #{hour |> zero_pad}:#{minute |> zero_pad}:#{second |> zero_pad}"
  end

  @spec zero_pad(Integer, Integer) :: String.t
  defp zero_pad(number, amount \\ 2) do
     number
     |> Integer.to_string
     |> String.rjust(amount, ?0)
  end

end

Here’s a gist.

Leave a Reply

Your email address will not be published. Required fields are marked *