From 9dd0414bb7da617d0cf4bfd375476c85f3be36f9 Mon Sep 17 00:00:00 2001 From: Anas Muhammad Date: Fri, 18 Sep 2026 18:06:44 +0500 Subject: [PATCH] fix: keep sign when zero-padding negative years in format('YYYY') (#2722) --- src/utils.js | 6 ++++-- test/display.test.js | 11 +++++++++++ test/utils.test.js | 10 ++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/utils.js b/src/utils.js index 324bc5e11..f13f13694 100644 --- a/src/utils.js +++ b/src/utils.js @@ -2,8 +2,10 @@ import * as C from './constant' const padStart = (string, length, pad) => { const s = String(string) - if (!s || s.length >= length) return string - return `${Array((length + 1) - s.length).join(pad)}${string}` + const neg = s[0] === '-' + const abs = neg ? s.slice(1) : s + if (!abs || abs.length >= length) return string + return `${neg ? '-' : ''}${Array((length + 1) - abs.length).join(pad)}${abs}` } const padZoneStr = (instance) => { diff --git a/test/display.test.js b/test/display.test.js index b98073cf2..30e360b3e 100644 --- a/test/display.test.js +++ b/test/display.test.js @@ -263,6 +263,17 @@ it('As ISO 8601 String -> toISOString e.g. 2013-02-04T22:44:30.652Z', () => { expect(dayjs().toISOString()).toBe(moment().toISOString()) }) +it('Negative years formatted with YYYY keep the sign and pad with zeroes', () => { + [[-1, '-0001'], [-10, '-0010'], [-100, '-0100'], [-1000, '-1000']].forEach(([year, expected]) => { + const date = new Date(0) + date.setFullYear(year, 5, 15) // mid-year so the local timezone cannot shift the year + expect(dayjs(date).format('YYYY')).toBe(expected) + expect(dayjs(date).format('YYYY')).toBe(moment(date).format('YYYY')) + }) + expect(dayjs('-000001-06-15').format('YYYY')).toBe('-0001') + expect(dayjs('-000001-06-15').year()).toBe(-1) +}) + 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 diff --git a/test/utils.test.js b/test/utils.test.js index 0d7e6e044..d0f49b96b 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -41,4 +41,14 @@ it('PadZoneStr', () => { it('PadStart', () => { expect(padStart(1, 2, '0')).toBe('01') expect(padStart(0, 2, '0')).toBe('00') + expect(padStart(123, 2, '0')).toBe(123) + expect(padStart('', 2, '0')).toBe('') +}) + +it('PadStart keeps the sign of negative numbers', () => { + expect(padStart(-1, 4, '0')).toBe('-0001') + expect(padStart(-10, 4, '0')).toBe('-0010') + expect(padStart(-100, 4, '0')).toBe('-0100') + expect(padStart(-1000, 4, '0')).toBe(-1000) + expect(padStart(-10000, 4, '0')).toBe(-10000) })