Skip to content

Commit f8285c7

Browse files
authored
find diff by duration hash instead of using repeated addition to cursor (#1340)
1 parent d607d8f commit f8285c7

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

src/impl/diff.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,22 @@ function highOrderDiffs(cursor, later, units) {
2222
];
2323

2424
const results = {};
25+
const earlier = cursor;
2526
let lowestOrder, highWater;
2627

2728
for (const [unit, differ] of differs) {
2829
if (units.indexOf(unit) >= 0) {
2930
lowestOrder = unit;
3031

31-
let delta = differ(cursor, later);
32-
highWater = cursor.plus({ [unit]: delta });
32+
results[unit] = differ(cursor, later);
33+
highWater = earlier.plus(results);
3334

3435
if (highWater > later) {
35-
cursor = cursor.plus({ [unit]: delta - 1 });
36-
delta -= 1;
36+
results[unit]--;
37+
cursor = earlier.plus(results);
3738
} else {
3839
cursor = highWater;
3940
}
40-
41-
results[unit] = delta;
4241
}
4342
}
4443

test/datetime/diff.test.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -295,14 +295,24 @@ test("DateTime#diff results in a duration with the same locale", () => {
295295

296296
// see https://github.com/moment/luxon/issues/487
297297
test("DateTime#diff results works when needing to backtrack months", () => {
298-
const left = DateTime.fromJSDate(new Date(1554036127038));
299-
const right = DateTime.fromJSDate(new Date(1554122527128));
298+
const left = DateTime.fromJSDate(new Date(1554036127038)); // 2019-03-31T12:42:07.038Z
299+
const right = DateTime.fromJSDate(new Date(1554122527128)); // 2019-04-01T12:42:07.128Z
300300

301301
const diff = right.diff(left, ["months", "days", "hours"]);
302302
expect(diff.months).toBe(0);
303303
expect(diff.days).toBe(1);
304304
});
305305

306+
// see https://github.com/moment/luxon/issues/1301
307+
test("DateTime#diff handles Feb-29 edge case logic for higher order units in a manner consistent with DateTime#plus", () => {
308+
const left = DateTime.fromISO("2020-02-29");
309+
const right = DateTime.fromISO("2021-04-01");
310+
311+
const diff = right.diff(left, ["years", "months", "days"]);
312+
expect(diff.days).toBe(3);
313+
expect(left.plus(diff).equals(right)).toBe(true);
314+
});
315+
306316
//------
307317
// diffNow
308318
//-------

0 commit comments

Comments
 (0)