fix(date): compute %U and %W week numbers like strftime (#958)

This commit is contained in:
web-orbit12
2026-09-27 14:47:52 +08:00
committed by GitHub
parent a2cdfb8aef
commit 0587ca803f
2 changed files with 19 additions and 6 deletions
+16
View File
@@ -140,6 +140,22 @@ describe('util/strftime', function () {
it('should format %W as week of year, starts with 1', function () { it('should format %W as week of year, starts with 1', function () {
expect(t(now, '%W')).toBe('01') expect(t(now, '%W')).toBe('01')
}) })
it('should format %U and %W as 00 before the first Sunday/Monday', function () {
// 2021-01-01 is a Friday
expect(t(new TestDate('2021-01-01 12:00:00'), '%U %W')).toBe('00 00')
expect(t(new TestDate('2021-01-03 12:00:00'), '%U %W')).toBe('01 00')
expect(t(new TestDate('2021-01-04 12:00:00'), '%U %W')).toBe('01 01')
})
it('should keep Sunday in the previous %W week', function () {
// 2000-01-02 is a Sunday
expect(t(new TestDate('2000-01-02 12:00:00'), '%W')).toBe('00')
expect(t(new TestDate('2000-01-09 12:00:00'), '%W')).toBe('01')
})
it('should format %U and %W when January 1st is the start day', function () {
// 2006-01-01 is a Sunday, 2007-01-01 is a Monday
expect(t(new TestDate('2006-07-05 12:00:00'), '%U %W')).toBe('27 27')
expect(t(new TestDate('2007-01-01 12:00:00'), '%U %W')).toBe('00 01')
})
}) })
describe('Time zone', () => { describe('Time zone', () => {
+3 -6
View File
@@ -23,12 +23,9 @@ function getDayOfYear (d: LiquidDate) {
return num + d.getDate() return num + d.getDate()
} }
function getWeekOfYear (d: LiquidDate, startDay: number) { function getWeekOfYear (d: LiquidDate, startDay: number) {
// Skip to startDay of this week // Days before the first startDay of the year belong to week 0
const now = getDayOfYear(d) + (startDay - d.getDay()) const daysSinceStartDay = (d.getDay() - startDay + 7) % 7
// Find the first startDay of the year return String(Math.floor((getDayOfYear(d) - 1 - daysSinceStartDay + 7) / 7))
const jan1 = new Date(d.getFullYear(), 0, 1)
const then = (7 - jan1.getDay() + startDay)
return String(Math.floor((now - then) / 7) + 1)
} }
function isLeapYear (d: LiquidDate) { function isLeapYear (d: LiquidDate) {
const year = d.getFullYear() const year = d.getFullYear()