]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
unit normalization for diff()
authorIsaac Cambron <icambron@gmail.com>
Mon, 8 Apr 2013 03:48:48 +0000 (23:48 -0400)
committerIsaac Cambron <icambron@gmail.com>
Mon, 8 Apr 2013 03:48:48 +0000 (23:48 -0400)
moment.js
test/moment/diff.js

index daaafe73009ad739fb02bccf8c966d36e03ff9ff..81a91da577d1e7a6549399658afc2d00e31aee22 100644 (file)
--- a/moment.js
+++ b/moment.js
     }
 
     function normalizeUnits(units) {
-        return unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1');
+        if (units) {
+            return unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1');
+        }
+        return units;
     }
 
 
                 zoneDiff = (this.zone() - that.zone()) * 6e4,
                 diff, output;
 
-            if (units) {
-                // standardize on singular form
-                units = units.replace(/s$/, '');
-            }
+            units = normalizeUnits(units);
 
             if (units === 'year' || units === 'month') {
                 diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
index 81edaad49df65968f2375f6f5673a12b18816eb4..957624582f2f2b3dd40e9ed33ba5231e31bf00d9 100644 (file)
@@ -67,6 +67,22 @@ exports.diff = {
         test.done();
     },
 
+    "diff key before abbreviated" : function(test) {
+        test.expect(10);
+
+        test.equal(moment([2011]).diff([2010], 'y'), 1, "year diff abbreviated");
+        test.equal(moment([2010, 2]).diff([2010], 'M'), 2, "month diff abbreviated");
+        test.equal(moment([2010, 0, 4]).diff([2010], 'd'), 3, "day diff abbreviated");
+        test.equal(moment([2010, 0, 7]).diff([2010], 'w'), 0, "week diff abbreviated");
+        test.equal(moment([2010, 0, 8]).diff([2010], 'w'), 1, "week diff abbreviated");
+        test.equal(moment([2010, 0, 21]).diff([2010], 'w'), 2, "week diff abbreviated");
+        test.equal(moment([2010, 0, 22]).diff([2010], 'w'), 3, "week diff abbreviated");
+        test.equal(moment([2010, 0, 1, 4]).diff([2010], 'h'), 4, "hour diff abbreviated");
+        test.equal(moment([2010, 0, 1, 0, 5]).diff([2010], 'm'), 5, "minute diff abbreviated");
+        test.equal(moment([2010, 0, 1, 0, 0, 6]).diff([2010], 's'), 6, "second diff abbreviated");
+        test.done();
+    },
+
     "diff month" : function(test) {
         test.expect(1);