Skip to content

Commit 64cd202

Browse files
lauJosé Valim
authored andcommitted
Allow more than Time structs in Time.diff/2
1 parent baf7b7a commit 64cd202

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

lib/elixir/lib/calendar/time.ex

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,14 @@ defmodule Time do
419419
end
420420

421421
@doc """
422-
Returns the difference between two `Time` structs.
422+
Returns the difference between two times, considering only the hour, minute
423+
second and microsecond.
424+
425+
As with the `compare/2` function both `Time` structs and other structures
426+
containing time can be used. If for instance a `NaiveDateTime` or `DateTime`
427+
is passed, only the hour, month, second, and microsecond is considered. Any
428+
additional information about a date or time zone is ignored when calculating
429+
the difference.
423430
424431
The answer can be returned in any `unit` available from
425432
`t:System.time_unit/0`. If the first unit is smaller than
@@ -432,14 +439,24 @@ defmodule Time do
432439
433440
iex> Time.diff(~T[00:29:12], ~T[00:29:10])
434441
2
442+
443+
# When passing a `NaiveDateTime` the date part is ignored.
444+
iex> Time.diff(~N[2017-01-01 00:29:12], ~T[00:29:10])
445+
2
446+
447+
# Two `NaiveDateTime` structs could have big differences in the date
448+
# but only the time part is considered.
449+
iex> Time.diff(~N[2017-01-01 00:29:12], (~N[1900-02-03 00:29:10]))
450+
2
451+
435452
iex> Time.diff(~T[00:29:12], ~T[00:29:10], :microsecond)
436453
2_000_000
437454
iex> Time.diff(~T[00:29:10], ~T[00:29:12], :microsecond)
438455
-2_000_000
439456
440457
"""
441-
@spec diff(t, t, System.time_unit) :: integer
442-
def diff(%Time{} = time1, %Time{} = time2, unit \\ :second) do
458+
@spec diff(Calendar.time, Calendar.time, System.time_unit) :: integer
459+
def diff(time1, time2, unit \\ :second) do
443460
fraction1 = to_day_fraction(time1)
444461
fraction2 = to_day_fraction(time2)
445462
Calendar.ISO.iso_days_to_unit({0, fraction1}, unit) -

0 commit comments

Comments
 (0)