Skip to content

Commit 3b9e891

Browse files
committed
Duration.toJSON() should not print unwanted zeroes
Due to a missing argument, Temporal.Duration.from({ hours: 1 }).toJSON() would return "PT1H0.0S" instead of "PT1H". The same goes for toLocaleString() in the absence of Intl.DurationFormat. No change needed to the spec text or documentation, which are already correct.
1 parent 5be251f commit 3b9e891

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

polyfill/lib/duration.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -562,15 +562,15 @@ export class Duration {
562562
}
563563
toJSON() {
564564
if (!ES.IsTemporalDuration(this)) throw new TypeError('invalid receiver');
565-
return ES.TemporalDurationToString(this);
565+
return ES.TemporalDurationToString(this, 'auto');
566566
}
567567
toLocaleString(locales = undefined, options = undefined) {
568568
if (!ES.IsTemporalDuration(this)) throw new TypeError('invalid receiver');
569569
if (typeof Intl !== 'undefined' && typeof Intl.DurationFormat !== 'undefined') {
570570
return new Intl.DurationFormat(locales, options).format(this);
571571
}
572572
console.warn('Temporal.Duration.prototype.toLocaleString() requires Intl.DurationFormat.');
573-
return ES.TemporalDurationToString(this);
573+
return ES.TemporalDurationToString(this, 'auto');
574574
}
575575
valueOf() {
576576
throw new TypeError('use compare() to compare Temporal.Duration');

polyfill/test/duration.mjs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,12 @@ describe('Duration', () => {
327327
[{}, () => {}, undefined].forEach((options) => equal(d1.toString(options), 'PT15H23M'));
328328
});
329329
});
330+
describe('toJSON()', () => {
331+
it('is like toString but always with auto precision', () => {
332+
const d = Duration.from({ hours: 1 });
333+
equal(d.toJSON(), d.toString({ fractionalSecondDigits: 'auto' }));
334+
});
335+
});
330336
describe('toLocaleString()', () => {
331337
it('produces an implementation-defined string', () => {
332338
const duration = Duration.from({ hours: 12, minutes: 30 });

0 commit comments

Comments
 (0)