]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Fix moment diff across dst in weird cases
authorIskren Chernev <iskren.chernev@gmail.com>
Sun, 10 Aug 2014 06:47:37 +0000 (23:47 -0700)
committerIskren Chernev <iskren.chernev@gmail.com>
Fri, 5 Sep 2014 04:51:21 +0000 (21:51 -0700)
moment diff across dst was sometimes failing because of a floating point
rounding. Just make sure to first do additions/subtractions and then division.

moment.js
test/moment/diff.js

index 2941b917056a6d858d474e7baaeb5c6a61560650..d49dee6062e99550dfe0625ebe9fd375e3f42d00 100644 (file)
--- a/moment.js
+++ b/moment.js
         diff : function (input, units, asFloat) {
             var that = makeAs(input, this),
                 zoneDiff = (this.zone() - that.zone()) * 6e4,
-                diff, output;
+                diff, output, daysAdjust;
 
             units = normalizeUnits(units);
 
                 output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
                 // adjust by taking difference in days, average number of days
                 // and dst in the given months.
-                output += ((this - moment(this).startOf('month')) -
-                        (that - moment(that).startOf('month'))) / diff;
+                daysAdjust = (this - moment(this).startOf('month')) -
+                    (that - moment(that).startOf('month'));
                 // same as above but with zones, to negate all dst
-                output -= ((this.zone() - moment(this).startOf('month').zone()) -
-                        (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
+                daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) -
+                        (that.zone() - moment(that).startOf('month').zone())) * 6e4;
+                output += daysAdjust / diff;
                 if (units === 'year') {
                     output = output / 12;
                 }
index 17a089a8f733fe3af77f9d2b659848111e2622f1..0e3de1ee7401d6646d68f450b5772cc5a3068e63 100644 (file)
@@ -226,7 +226,21 @@ exports.diff = {
         test.done();
     },
 
-    'year diffs' : function (test) {
+    "exact month diffs" : function (test) {
+        // generate all pairs of months and compute month diff, with fixed day
+        // of month = 15.
+
+        var m1, m2;
+        for (m1 = 0; m1 < 12; ++m1) {
+            for (m2 = m1; m2 < 12; ++m2) {
+                test.equal(moment([2013, m2, 15]).diff(moment([2013, m1, 15]), 'months', true), m2 - m1,
+                        "month diff from 2013-" + m1 + "-15 to 2013-" + m2 + "-15");
+            }
+        }
+        test.done();
+    },
+
+    "year diffs" : function (test) {
         test.expect(10);
 
         // due to floating point math errors, these tests just need to be accurate within 0.00000001