Epoch in Elixir

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Elixir.

defmodule Epoch do
  def main do
    now = DateTime.utc_now()
    IO.puts(now)

    # Get seconds, milliseconds, and nanoseconds since Unix epoch
    IO.puts(DateTime.to_unix(now))
    IO.puts(DateTime.to_unix(now, :millisecond))
    IO.puts(DateTime.to_unix(now, :nanosecond))

    # Convert integer seconds or nanoseconds since the epoch into DateTime
    IO.puts(DateTime.from_unix!(DateTime.to_unix(now)))
    IO.puts(DateTime.from_unix!(DateTime.to_unix(now, :nanosecond), :nanosecond))
  end
end

Epoch.main()

Use DateTime.utc_now() to get the current UTC time. Then, use DateTime.to_unix/2 to get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds.

You can also convert integer seconds or nanoseconds since the epoch into the corresponding DateTime using DateTime.from_unix!/2.

To run the program:

$ elixir epoch.exs
2023-05-24 12:34:56.789012Z
1684931696
1684931696789
1684931696789012000
2023-05-24 12:34:56Z
2023-05-24 12:34:56.789012Z

Next, we’ll look at another time-related task: time parsing and formatting.