From: Ash Searle Date: Tue, 11 Jul 2017 18:31:02 +0000 (+0100) Subject: Fix toString for durations with mixed sign X-Git-Tag: 2.19.0~8^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=effaf874ad79b809cce35583f62334f37e630fae;p=thirdparty%2Fmoment.git Fix toString for durations with mixed sign --- diff --git a/src/lib/duration/iso-string.js b/src/lib/duration/iso-string.js index aafbb4cdb..721cec4a8 100644 --- a/src/lib/duration/iso-string.js +++ b/src/lib/duration/iso-string.js @@ -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' : ''); } diff --git a/src/test/moment/duration.js b/src/test/moment/duration.js index 6f0f65dc3..fb7c907ce 100644 --- a/src/test/moment/duration.js +++ b/src/test/moment/duration.js @@ -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');