]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Fix toString for durations with mixed sign
authorAsh Searle <ash@hexmen.com>
Tue, 11 Jul 2017 18:31:02 +0000 (19:31 +0100)
committerIskren Chernev <iskren.chernev@gmail.com>
Mon, 9 Oct 2017 22:46:58 +0000 (01:46 +0300)
src/lib/duration/iso-string.js
src/test/moment/duration.js

index aafbb4cdb65818eadf767c98ede5ee71447b2c42..721cec4a85ced7fdd7ea171f8f657782bec1a3b2 100644 (file)
@@ -38,19 +38,23 @@ export function toISOString() {
     var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
     var total = this.asSeconds();
 
+    var totalSign = total < 0 ? '-' : '';
+    var ymSign = Math.sign(total) === Math.sign(this._months) ? '' : '-';
+    var daysSign = Math.sign(total) === Math.sign(this._days) ? '' : '-';
+    var hmsSign = Math.sign(total) === Math.sign(this._milliseconds) ? '' : '-';
+
     if (!total) {
         // this is the same as C#'s (Noda) and python (isodate)...
         // but not other JS (goog.date)
         return 'P0D';
     }
 
-    return (total < 0 ? '-' : '') +
-        'P' +
-        (Y ? Y + 'Y' : '') +
-        (M ? M + 'M' : '') +
-        (D ? D + 'D' : '') +
+    return totalSign + 'P' +
+        (Y ? ymSign + Y + 'Y' : '') +
+        (M ? ymSign + M + 'M' : '') +
+        (D ? daysSign + D + 'D' : '') +
         ((h || m || s) ? 'T' : '') +
-        (h ? h + 'H' : '') +
-        (m ? m + 'M' : '') +
-        (s ? s + 'S' : '');
+        (h ? hmsSign + h + 'H' : '') +
+        (m ? hmsSign + m + 'M' : '') +
+        (s ? hmsSign + s + 'S' : '');
 }
index 6f0f65dc3799d1a48a2861a36b0dd93968701843..fb7c907ce1cf974d3c6653c3faefa22d3908660d 100644 (file)
@@ -334,6 +334,7 @@ test('serialization to ISO 8601 duration strings', function (assert) {
     assert.equal(moment.duration({m: +1}).toISOString(), 'PT1M', 'one minute ago');
     assert.equal(moment.duration({s: +0.5}).toISOString(), 'PT0.5S', 'one half second ago');
     assert.equal(moment.duration({y: +1, M: 1}).toISOString(), 'P1Y1M', 'a month after a year in future');
+    assert.equal(moment.duration({y: -1, h: 1}).toISOString(), '-P1YT-1H', 'an hour after a year ago');
     assert.equal(moment.duration({}).toISOString(), 'P0D', 'zero duration');
     assert.equal(moment.duration({M: 16, d:40, s: 86465}).toISOString(), 'P1Y4M40DT24H1M5S', 'all fields');
     assert.equal(moment.duration({ms: 123456789}).toISOString(), 'PT34H17M36.789S', 'check floating-point errors');