For Developers

Unix Timestamp in Elixir

How to get the current timestamp, convert it to a date, and convert a date back to a timestamp in Elixir, using the standard library's DateTime module.

ts = DateTime.utc_now() |> DateTime.to_unix()
ts = 1750000000
{:ok, dt} = DateTime.from_unix(ts)
IO.inspect(dt) # ~U[2025-06-15 12:00:00Z]
{:ok, dt} = DateTime.new(~D[2025-06-15], ~T[12:00:00], "Etc/UTC")
ts = DateTime.to_unix(dt)

The Elixir-specific pitfall

Elixir's DateTime is timezone-aware by design, but the standard library only ships with the "Etc/UTC" zone built in — converting to or from any named zone like "America/New_York" requires a separate timezone database library (commonly tzdata paired with a wrapper like Timex). Code that calls DateTime.new/3 with a zone name the runtime doesn't have data for raises a runtime error rather than silently falling back to UTC, which is safer behavior but does mean the dependency has to be set up correctly before any non-UTC conversion will work at all.

Have a timestamp right now?

Paste it into the Timestamp ⇄ Date Converter to check it instantly, in any timezone, without writing any code. Working across several languages on the same project? The full Epoch Time in Programming Languages guide has all of them side by side for quick comparison.

Related

Related tools & reading