]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Use month with bigger date first when computing month diffs
authorIskren Chernev <iskren.chernev@gmail.com>
Wed, 29 Apr 2020 15:56:37 +0000 (18:56 +0300)
committerIskren Chernev <iskren.chernev@gmail.com>
Wed, 29 Apr 2020 15:56:37 +0000 (18:56 +0300)
src/lib/moment/diff.js
src/test/moment/diff.js

index baa3f7184d38a1b84d6137e2fce2fcf593e06628..5157318c4f698de43ff0cc97459700c978359d15 100644 (file)
@@ -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)
index 47ad599d232e506c7c2e80014e22ec2b8496455d..279b8a8f8027fb66514f20f7f9ef2d757149dc78 100644 (file)
@@ -210,13 +210,36 @@ test('diff month', function (assert) {
 });
 
 test('end of month diff', function (assert) {
-    assert.equal(moment([2016, 1, 29]).diff([2016, 0, 30], 'months'), 1, 'Feb 29 to Jan 30 should be 1 month');
-    assert.equal(moment([2016, 1, 29]).diff([2016, 0, 31], 'months'), 1, 'Feb 30 to Jan 31 should be 1 month');
-    assert.equal(moment([2016, 4, 31]).add(1,'month').diff(moment([2016, 4, 31]), 'month'), 1, '(May 31 plus 1 month) to May 31 should be 1 month diff');
+    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, 2, 31, 1]).diff([2017, 1, 28, 2], 'months'), 1, 'Feb 28 to March 31 should be 1 month');
+    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) {