From 37dbef2b4c26823838e1abb3131a1199aad31017 Mon Sep 17 00:00:00 2001 From: Adam Hellberg Date: Tue, 7 Feb 2023 10:18:56 +0100 Subject: [PATCH 1/2] Add missing padding to 'YYYY' format Adds padding to the year component when formatted with `'YYYY'`, similar to how padding is handled for '`MM`' and '`DD`'. Fixes #2230 --- src/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 19c409078..ba74b8b66 100644 --- a/src/index.js +++ b/src/index.js @@ -280,7 +280,7 @@ class Dayjs { const matches = { YY: String(this.$y).slice(-2), - YYYY: this.$y, + YYYY: Utils.s(this.$y, 4, '0'), M: $M + 1, MM: Utils.s($M + 1, 2, '0'), MMM: getShort(locale.monthsShort, $M, months, 3), From ea97f4cfed6edff8d1985fa5768d63975118ee17 Mon Sep 17 00:00:00 2001 From: Adam Hellberg Date: Sat, 11 Feb 2023 14:38:57 +0100 Subject: [PATCH 2/2] Add some tests for 'YYYY' format --- test/display.test.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/display.test.js b/test/display.test.js index 7eb48fe82..86a978dfc 100644 --- a/test/display.test.js +++ b/test/display.test.js @@ -260,3 +260,15 @@ it('As JSON -> toJSON', () => { it('As ISO 8601 String -> toISOString e.g. 2013-02-04T22:44:30.652Z', () => { expect(dayjs().toISOString()).toBe(moment().toISOString()) }) + +it('Year 1 formatted with YYYY should pad with zeroes', () => { + const date = new Date(1, 0, 1) + date.setUTCFullYear(1) // Required because 0-99 are parsed as 19xx in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#year + expect(dayjs(date).format('YYYY')).toBe('0001') +}) + +it('Year 1 formatting matches moment format', () => { + const date = new Date(1, 0, 1) + date.setUTCFullYear(1) + expect(dayjs(date).format('YYYY')).toBe(moment(date).format('YYYY')) +})