Date and Time

Working with time in Elixir.

Table of Contents


Elixir has some modules which work with time. Though it needs to be noted that this functionality is limited to working with UTC timezone.

Let’s start with getting the current time:

iex> Time.utc_now

Note that we have a sigil which can be used to create a Time struct as well:

iex> ~T[19:39:31.056226]

You can learn more about sigils in the lesson about sigils. It is easy to access parts of this struct:

iex> t = ~T[19:39:31.056226]
iex> t.hour
iex> t.minute
** (KeyError) key :day not found in: ~T[19:39:31.056226]

But there is a catch: as you may have noticed, this struct only contains the time within a day, no day/month/year data is present.


Contary to Time, a Date struct has info about the current date, without any info about current time.

iex> Date.utc_today

And it has some useful functions to work with dates:

iex> {:ok, date} =, 12,12)
{:ok, ~D[2020-12-12]}
iex> Date.day_of_week date
iex> Date.leap_year? date

day_of_week/1 calculates which day of the week a given date is on. In this case it’s Saturday. leap_year?/1 checks whether this is a leap year. Other functions can be found in doc.


There are two kinds of structs which contain both date and time at once in Elixir. The first is NaiveDateTime. Its disadvantage is lack of timezone support:

iex(15)> NaiveDateTime.utc_now
~N[2029-01-21 19:55:10.008965]

But it has both the current time and date, so you can play with adding time, for example:

iex> NaiveDateTime.add(~N[2018-10-01 00:00:14], 30)
~N[2018-10-01 00:00:44]


The second, as you may have guessed from title of this section, is DateTime. It does not have the limitations noted in NaiveDateTime: it has both time and date, and supports timezones. But be aware about timezones. The official docs state:

You will notice this module only contains conversion functions as well as functions that work on UTC.
This is because a proper DateTime implementation requires a time zone database which currently is not provided as part of Elixir.

Also, note that you can create a DateTime instance from the NaiveDateTime, just by providing the timezone:

iex> DateTime.from_naive(~N[2016-05-24 13:26:08.003], "Etc/UTC")
{:ok, #DateTime<2016-05-24 13:26:08.003Z>}

This is it! If you want to work with other advanced functions you may want to consider looking futher into docs for Time, Date, DateTime and NaiveDateTime You should also consider Timex and Calendar which are powerful libraries to work with time in Elixir.

Caught a mistake or want to contribute to the lesson? Edit this page on GitHub!