Skip to content

Commit eb119df

Browse files
committed
Add a section on comparing durations, closes #14472
1 parent 170b797 commit eb119df

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

lib/elixir/lib/calendar/duration.ex

+24
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,30 @@ defmodule Duration do
9191
The second example consistently points to the last day of the month,
9292
as it performs operations on the duration, rather than shifting date
9393
after date.
94+
95+
## Comparing durations
96+
97+
In order to accurately compare durations, you need to either compare
98+
only certain fields or use a refernce time instant. This is because
99+
some fields are relative to others. For example, you may say that
100+
1 month is the same as 30 days, but if you add both of these durations
101+
to `~D[2015-02-01]`, you would get different results, as that month
102+
has only 28 days.
103+
104+
Therefore, if you wish to compare durations, one option is to use
105+
`Date.shift/2` (or `DateTime.shift/2` or similar), and then compare
106+
the dates:
107+
108+
iex> date = ~D[2015-02-01]
109+
iex> Date.compare(Date.shift(date, month: 1), Date.shift(date, day: 30))
110+
:lt
111+
112+
Or alternatively convert the durations to a fixed unit by using `to_timeout/1`,
113+
which supports durations only up to weeks, raising if it has the month or year
114+
fields set.
115+
116+
iex> to_timeout(hour: 24) == to_timeout(day: 1)
117+
true
94118
"""
95119

96120
@moduledoc since: "1.17.0"

0 commit comments

Comments
 (0)