Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/elixir/lib/calendar/naive_datetime.ex
Original file line number Diff line number Diff line change
Expand Up @@ -570,9 +570,11 @@ defmodule NaiveDateTime do
"unsupported time unit. Expected :day, :hour, :minute, :second, :millisecond, :microsecond, :nanosecond, or a positive integer, got #{inspect(unit)}"
end

units1 = naive_datetime1 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit)
units2 = naive_datetime2 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit)
units1 - units2
diff_microsecond =
(naive_datetime1 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(:microsecond)) -
(naive_datetime2 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(:microsecond))

System.convert_time_unit(diff_microsecond, :microsecond, unit)
end

@doc """
Expand Down
23 changes: 23 additions & 0 deletions lib/elixir/test/elixir/calendar/naive_datetime_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,29 @@ defmodule NaiveDateTimeTest do

assert NaiveDateTime.diff(%{dt | second: 57}, dt, :second) == 50
end

test "truncates the elapsed difference, not each operand (matches DateTime.diff)" do
# The true elapsed span is 0.5s (< 1s) and 86399.5s (< 1 day). Sub-second
# fractions must not inflate the count: per the "rounds incomplete days to
# zero" guarantee, and consistent with the sibling DateTime.diff/3.
assert NaiveDateTime.diff(
~N[2000-01-01 00:00:01.200000],
~N[2000-01-01 00:00:00.700000],
:second
) == 0

assert NaiveDateTime.diff(
~N[2000-01-02 00:00:00.200000],
~N[2000-01-01 00:00:00.700000],
:day
) == 0

assert NaiveDateTime.diff(
~N[2000-01-01 00:00:00.001200],
~N[2000-01-01 00:00:00.000700],
:millisecond
) == 0
end
end

test "convert/2" do
Expand Down
Loading