diff --git a/src/weekUtils.ts b/src/weekUtils.ts index 7775ef1..195ab40 100644 --- a/src/weekUtils.ts +++ b/src/weekUtils.ts @@ -1,32 +1,6 @@ -export const getStartOfWeek = (date: Date) => { - const startOfWeek = new Date(date); - const diffDays = startOfWeek.getDay(); - startOfWeek.setDate(startOfWeek.getDate() - diffDays); - startOfWeek.setHours(0, 0, 0, 0); - return startOfWeek; -}; - -const areDatesInSameWeek = (date1: Date, date2: Date) => { - const startOfWeek1 = getStartOfWeek(date1); - const startOfWeek2 = getStartOfWeek(date2); - return startOfWeek1.getTime() === startOfWeek2.getTime(); -}; - -export const getWeekNumber = (date: Date): number => { - const jan1st = new Date(date.getFullYear(), 0, 1); - const daysFromJan1UntilDate = Math.floor((date.getTime() - jan1st.getTime()) / (24 * 60 * 60 * 1000)); - const offsetFromJan1ToSundaySameWeek = -(jan1st.getDay() % 7) % 7; - const weeksRaw = (daysFromJan1UntilDate + offsetFromJan1ToSundaySameWeek) / 7; - - const weekOfDate = - (weeksRaw >= 0 ? Math.floor(weeksRaw) : Math.ceil(weeksRaw)) + (daysFromJan1UntilDate !== 365 ? 1 : 0); - - const lastDayOfPreviousYear = new Date(date.getFullYear() - 1, 11, 31); - - if (weekOfDate === 1 && areDatesInSameWeek(lastDayOfPreviousYear, date)) - return getWeekNumber(lastDayOfPreviousYear); - - return weekOfDate; +export const getWeekNumber = (date: Date) => { + const onejan = new Date(date.getFullYear(), 0, 1); + return Math.ceil(((date.getTime() - onejan.getTime()) / 86400000 + onejan.getDay() + 1) / 7); }; export const getWeekOfYear = (): number => getWeekNumber(new Date()); diff --git a/test/weekUtils.spec.ts b/test/weekUtils.spec.ts index f9eec46..b86f5e8 100644 --- a/test/weekUtils.spec.ts +++ b/test/weekUtils.spec.ts @@ -7,7 +7,7 @@ describe('weekUtils', () => { expect(getWeekNumber(date1)).toBe(53); const date2 = new Date('2025-01-01'); - expect(getWeekNumber(date2)).toBe(52); + expect(getWeekNumber(date2)).toBe(53); }); });