Skip to content

Commit

Permalink
Merge pull request #4717 from asenousy:end-of-month-diff-bugs
Browse files Browse the repository at this point in the history
[bugfix] More predictable month diffs at end-of-month
  • Loading branch information
ichernev committed Apr 29, 2020
2 parents c78af30 + a63b46a commit 813eb32
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/lib/moment/diff.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ export function diff(input, units, asFloat) {
}

function monthDiff(a, b) {
if (a.date() < b.date()) {
// end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
}
// difference in months
var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
Expand Down
33 changes: 33 additions & 0 deletions src/test/moment/diff.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,39 @@ test('diff month', function (assert) {
);
});

test('end of month diff', function (assert) {
assert.equal(
moment('2016-02-29').diff('2016-01-30', 'months'),
1,
'Feb 29 to Jan 30 should be 1 month'
);
assert.equal(
moment('2016-02-29').diff('2016-01-31', 'months'),
1,
'Feb 29 to Jan 31 should be 1 month'
);
assert.equal(
moment('2016-05-31')
.add(1, 'month')
.diff(moment('2016-05-31'), 'month'),
1,
'(May 31 plus 1 month) to May 31 should be 1 month diff'
);
});

test('end of month diff with time behind', function (assert) {
assert.equal(
moment('2017-03-31').diff('2017-02-28', 'months'),
1,
'Feb 28 to March 31 should be 1 month'
);
assert.equal(
moment('2017-02-28').diff('2017-03-31', 'months'),
-1,
'Feb 28 to March 31 should be 1 month'
);
});

test('diff across DST', function (assert) {
var dst = dstForYear(2012),
a,
Expand Down

0 comments on commit 813eb32

Please sign in to comment.