From 00c223b7e92970d07557133994fcb225a6d4c960 Mon Sep 17 00:00:00 2001 From: Adam Hellberg Date: Mon, 13 Feb 2023 05:32:05 +0100 Subject: [PATCH] fix: .format add padding to 'YYYY' (#2231) --- src/index.js | 2 +- test/display.test.js | 12 ++++++++++++ 2 files changed, 13 insertions(+), 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), 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')) +})