fix(date): compute %C and %y from the numeric year (#961)

Both were sliced from the year string, so years with other than four
digits gave the wrong century and two-digit year, and %y was a string
that the - and _ flags could not unpad. Compute them arithmetically and
pad them to two digits, matching Ruby's strftime.
This commit is contained in:
KBS
2026-09-30 00:47:25 +08:00
committed by GitHub
parent 28ae3fba5d
commit e68514f066
2 changed files with 13 additions and 3 deletions
+8
View File
@@ -18,6 +18,14 @@ describe('util/strftime', function () {
it('should format %y as 2-digit year', function () {
expect(t(now, '%y')).toBe('16')
})
it('should format %C and %y from the numeric year', function () {
const year999 = new TestDate('0999-06-15 00:00:00')
expect(t(year999, '%C')).toBe('09')
expect(t(year999, '%y')).toBe('99')
const year2005 = new TestDate('2005-06-15 00:00:00')
expect(t(year2005, '%y')).toBe('05')
expect(t(year2005, '%-y')).toBe('5')
})
describe('%j', function () {
it('should format %j as day of year', function () {
expect(t(then, '%j')).toBe('066')
+5 -3
View File
@@ -43,11 +43,12 @@ function ordinal (d: LiquidDate) {
}
}
function century (d: LiquidDate) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10)
return Math.floor(d.getFullYear() / 100)
}
// default to 0
const padWidths: Record<string, number> = {
C: 2,
d: 2,
e: 2,
H: 2,
@@ -60,7 +61,8 @@ const padWidths: Record<string, number> = {
M: 2,
S: 2,
U: 2,
W: 2
W: 2,
y: 2
}
const padSpaceChars = new Set('aAbBceklpP')
@@ -110,7 +112,7 @@ const formatCodes: Record<string, FormatCodeHandler> = {
W: (d: LiquidDate) => getWeekOfYear(d, 1),
x: (d: LiquidDate) => d.toLocaleDateString(),
X: (d: LiquidDate) => d.toLocaleTimeString(),
y: (d: LiquidDate) => d.getFullYear().toString().slice(2, 4),
y: (d: LiquidDate) => (d.getFullYear() % 100 + 100) % 100,
Y: (d: LiquidDate) => d.getFullYear(),
z: getTimezoneOffset,
Z: (d: LiquidDate, opts: FormatOptions) => d.getTimeZoneName() || getTimezoneOffset(d, opts),