Date and Time

Elixir has four primary date/time types:

  • Date - Just date
  • Time - Just time
  • NaiveDateTime - Date and time without timezone
  • DateTime - Date and time with timezone
Date.new(2025, 5, 2)
# {:ok, ~D[2025-05-02]}
Date.new(2025, 5, 32)
# {:error, :invalid_date}
Time.new(23, 59, 59)
# {:ok, ~T[23:59:59]}
Time.new(24, 0, 0)
# {:error, :invalid_time}
NaiveDateTime.new(2025, 5, 2, 23, 59, 59)
# {:ok, ~N[2025-05-02 23:59:59]}
DateTime.new(Date.utc_today(), Time.utc_now())
# {:ok, ~U[2025-05-02 23:59:59.802817Z]}
DateTime.utc_now()
# ~U[2025-05-02 23:59:59.931917Z]

Manipulations

Date.diff(~D[2025-05-02], ~D[2025-05-08])
# -6
Date.add(~D[2025-05-02], 365)
# ~D[2026-05-02]
DateTime.compare(~U[2025-05-02 23:59:59Z], DateTime.utc_now())
# :lt

Formating

Calendar.strftime(~U[2025-05-02 23:59:59Z], "%Y-%m-%d %H:%M:%S")
# "2025-05-02 23:59:59"
DateTime.shift_zone(~U[2025-05-02 23:59:59Z], "Asia/Tokyo")
# {:error, :utc_only_time_zone_database}