From 890a17a8d8ddd43c7c8b806e3afc7b27f3288d27 Mon Sep 17 00:00:00 2001 From: Creed Haymond Date: Tue, 4 Jul 2023 22:25:30 -0600 Subject: [PATCH] fix: round durations to millisecond precision for ISO string (#2367) --- src/plugin/duration/index.js | 2 +- test/plugin/duration.test.js | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/plugin/duration/index.js b/src/plugin/duration/index.js index 26bc75e34..d7adf7517 100644 --- a/src/plugin/duration/index.js +++ b/src/plugin/duration/index.js @@ -139,7 +139,7 @@ class Duration { let seconds = this.$d.seconds || 0 if (this.$d.milliseconds) { - seconds += this.$d.milliseconds / 1000 + seconds += Math.round(this.$d.milliseconds) / 1000 } const S = getNumberUnitFormat(seconds, 'S') diff --git a/test/plugin/duration.test.js b/test/plugin/duration.test.js index 4a4753931..eec20b1e3 100644 --- a/test/plugin/duration.test.js +++ b/test/plugin/duration.test.js @@ -70,6 +70,13 @@ describe('Creating', () => { it('convert to milliseconds', () => { expect(+dayjs.duration(100)).toBe(100) }) + it('handles rounding to millisecond precision', () => { + expect(dayjs.duration(2 / 3).toISOString()).toBe('PT0.001S') + }) + it('should handle round with millisecond precision when negative', () => { + expect(dayjs.duration(1000.5).toISOString()).toBe('PT1.001S') + expect(dayjs.duration(-1000.5).toISOString()).toBe('-PT1S') + }) }) describe('Parse ISO string', () => {