Calculating a date in the future or past

Elixir:
Calculating a date in the future or past

How to:

Using Elixir’s built-in Date module, you can easily play with the timeline.

# Add to or subtract from a given date
date_today = ~D[2023-04-15]
{year, month, day} = date_today

# Calculate a date 10 days in the future
date_future = Date.add(date_today, 10)
IO.inspect(date_future)  # => ~D[2023-04-25]

# Calculate a date 30 days in the past
date_past = Date.add(date_today, -30)
IO.inspect(date_past)  # => ~D[2023-03-16]

Notice how Date.add/2 simply takes the number of days you want to travel in the time continuum.

Deep Dive

The ability to compute dates in the future or past isn’t new. Historical programming languages also had their ways—think COBOL or FORTRAN. However, Elixir brings functional flair and the immutability of data to the table, making date calculations straightforward and less prone to errors.

Alternatives? You could manually calculate by adding seconds, minutes, and so on, but why reinvent the wheel when Elixir provides a robust Date module? Especially considering time-based calculations can get complex, accounting for leap years, time zones, and daylight saving changes.

Implementation details revolve around understanding Elixir’s :calendar module and the underlying Erlang implementations. We’re standing on the shoulders of eras of date and time functionality evolution, with Elixir’s syntax sugar making it all the sweeter.

See Also