Unix Timestamp in Elixir

Elixir uses DateTime and System.system_time/1 for Unix timestamps. Both return integers in the time unit you specify (:second, :millisecond, :microsecond) — making unit conversion explicit and clear.

Ad

Code Examples

Current timestamp (seconds)

System.system_time(:second)

Returns the current Unix timestamp in seconds as an integer. The :second unit is the most common for REST APIs and database storage.

Current timestamp (milliseconds)

System.system_time(:millisecond)

Returns milliseconds since epoch. Pass :microsecond for even finer precision. These are native Erlang/OTP time units.

Using DateTime module

DateTime.utc_now() |> DateTime.to_unix(:second)

Pipeline-style: get the current UTC DateTime, then convert to Unix seconds. Prefer this in Phoenix/Ecto code where you're already working with DateTime structs.

Convert timestamp back to DateTime

DateTime.from_unix!(1708560000, :second)

Converts a Unix timestamp to a DateTime struct in UTC. The bang (!) variant raises if the timestamp is out of range; use DateTime.from_unix/2 for the {:ok, dt} tuple form.

Ecto — inserting a timestamp

# In a migration or changeset:
NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)

Ecto typically stores timestamps as NaiveDateTime (UTC, no timezone). truncate/1 removes sub-second precision, which most databases don't store by default.

Note

Elixir inherits Erlang's time handling — System.system_time/1 is the idiomatic choice for Unix timestamps. In Phoenix/Ecto applications, DateTime.utc_now() is preferred because it returns a DateTime struct you can pipe directly into Ecto changesets and schema fields.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter