From b3d91fb2dae40eee1cbc17b6f6ddaaf3922fb21d Mon Sep 17 00:00:00 2001 From: ChaiyoKung Date: Tue, 19 Nov 2024 12:40:10 +0700 Subject: [PATCH 1/2] fix: wrong ms conversion --- src/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 061ade178..86e48ff23 100644 --- a/src/index.js +++ b/src/index.js @@ -69,7 +69,8 @@ const parseDate = (cfg) => { const d = date.match(C.REGEX_PARSE) if (d) { const m = d[2] - 1 || 0 - const ms = (d[7] || '0').substring(0, 3) + const msLength = 3 + const ms = (d[7] || '0').substring(0, msLength).padEnd(msLength, '0') if (utc) { return new Date(Date.UTC(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)) From c081100c7bba01337afcb6899408b26b570c035c Mon Sep 17 00:00:00 2001 From: ChaiyoKung Date: Tue, 19 Nov 2024 12:42:38 +0700 Subject: [PATCH 2/2] test: add test for issue#2769 --- .../issue2769.wrong-ms-conversion.test.js | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 test/issues/issue2769.wrong-ms-conversion.test.js diff --git a/test/issues/issue2769.wrong-ms-conversion.test.js b/test/issues/issue2769.wrong-ms-conversion.test.js new file mode 100644 index 000000000..84a3f4b8b --- /dev/null +++ b/test/issues/issue2769.wrong-ms-conversion.test.js @@ -0,0 +1,34 @@ +import MockDate from 'mockdate' +import dayjs from '../../src' + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +describe('issue 2769 - wrong ms conversion', () => { + it('should correctly convert date string without timezone', () => { + const ds1 = '2024-11-18T02:04:48' + expect(dayjs(ds1).valueOf()).toEqual(new Date(ds1).valueOf()) + const ds2 = '2024-11-18T02:04:48.3' + expect(dayjs(ds2).valueOf()).toEqual(new Date(ds2).valueOf()) + const ds3 = '2024-11-18T02:04:48.19' + expect(dayjs(ds3).valueOf()).toEqual(new Date(ds3).valueOf()) + const ds4 = '2024-11-18T02:04:48.195' + expect(dayjs(ds4).valueOf()).toEqual(new Date(ds4).valueOf()) + }) + + it('should correctly convert date string with timezone', () => { + const ds1 = '2024-11-18T02:04:48Z' + expect(dayjs(ds1).valueOf()).toEqual(new Date(ds1).valueOf()) + const ds2 = '2024-11-18T02:04:48.3Z' + expect(dayjs(ds2).valueOf()).toEqual(new Date(ds2).valueOf()) + const ds3 = '2024-11-18T02:04:48.19Z' + expect(dayjs(ds3).valueOf()).toEqual(new Date(ds3).valueOf()) + const ds4 = '2024-11-18T02:04:48.195Z' + expect(dayjs(ds4).valueOf()).toEqual(new Date(ds4).valueOf()) + }) +})