Elixir Dates and Times
A date is a calendar day given by its year, month, and day. Elixir stores a date in a Date value and offers functions to build, move, and compare dates.
A built date prints as 2026-10-28
Date.new! builds a date from a year, a month, and a day. Date.to_string turns it into text.
date = Date.new!(2026, 10, 28)
IO.puts(Date.to_string(date))
IO.inspect(date)2026-10-28 is weekday 3, a Wednesday
Date.day_of_week counts Monday as 1. The fixed date below answers 3.
date = ~D[2026-10-28]
IO.puts(Date.day_of_week(date))
later = Date.add(date, 7)
IO.puts(Date.to_string(later))The gap between two fixed dates is 7 days
Date.diff counts the days between two dates. The two dates below sit one week apart.
IO.puts(Date.diff(~D[2026-10-28], ~D[2026-10-21]))
IO.puts(Date.diff(~D[2026-10-21], ~D[2026-10-28]))Example
start = Date.new!(2026, 10, 28)
finish = Date.add(start, 14)
IO.puts(Date.to_string(start))
IO.puts(Date.day_of_week(start))
IO.puts(Date.to_string(finish))
IO.puts(Date.diff(finish, start))Key points
- Literal: ~D[2026-10-28] writes a date directly in a script.
- Build: Date.new!(2026, 10, 28) builds the same date from three numbers.
- Weekday: Date.day_of_week answers a number from 1 for Monday to 7 for Sunday.
- Add: Date.add(date, 7) returns a new date seven days later.
- Difference: Date.diff(a, b) counts the days from b to a.
- Text: Date.to_string turns a date into text like 2026-10-28.
In this example, the script builds the fixed start date 2026-10-28 with Date.new!. It adds 14 days to get the finish date. It prints the start as text, its weekday number 3, the finish as text, and the 14-day gap between them.
Note
this lesson always uses the fixed date 2026-10-28, never the day the script runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Date.add(~D[2026-10-28], 7) return?