getWeekNumber
Returns the ISO 8601 week number for a given date. The week starts on Monday and the first week of the year is the one that contains January 4th.
1/**
2 * Returns the ISO 8601 week number for a given date.
3 * The week starts on Monday and the first week of the year is the one that contains January 4th.
4 *
5 * @param date - The date to get the week number for.
6 * @returns The ISO week number (1–53).
7 */
8export function getWeekNumber(date: Date): number {
9 const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
10 const day = d.getUTCDay() || 7;
11
12 d.setUTCDate(d.getUTCDate() + 4 - day);
13
14 const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
15 const weekNo = Math.ceil(((+d - +yearStart) / 86400000 + 1) / 7);
16
17 return weekNo;
18}
ISO 8601 Compliance
Correctly implements the ISO standard, where weeks start on Monday and the first week contains January 4th — useful for international consistency.
Timezone-Agnostic via UTC
Uses
Date.UTC
andgetUTC*
methods to avoid discrepancies caused by local timezones.Pure Functionality
Stateless and deterministic — always returns the same result for the same input without side effects.
Mathematically Precise Week Calculation
Accurately calculates week boundaries by aligning the input date to the nearest ISO week frame.
No External Dependencies
Achieves standards-compliant results without relying on third-party libraries like
date-fns
ormoment
.
Tests | Examples
1test('getWeekNumber - returns correct week number for Jan 1st', () => {
2 expect(getWeekNumber(new Date('2024-01-01'))).toBe(1);
3});
4
5test('getWeekNumber - mid-year date', () => {
6 expect(getWeekNumber(new Date('2024-07-01'))).toBe(27);
7});
8
9test('getWeekNumber - end of year edge case', () => {
10 expect(getWeekNumber(new Date('2021-12-31'))).toBe(52);
11});
12
13test('getWeekNumber - first week of year that starts midweek', () => {
14 expect(getWeekNumber(new Date('2020-01-01'))).toBe(1);
15});
Common Use Cases
Weekly Reports and Metrics
Assign records or transactions to specific ISO week numbers for analysis or reporting.
Payroll or Scheduling Systems
Group working days and time entries into consistent weekly blocks.
Calendar-Based UI Components
Highlight or display week numbers in date pickers or visual calendars.
Data Aggregation by Week
Useful for bucketing or summarizing events based on their week of occurrence.
Compliance with Business or Regional Standards
Required in systems operating in countries or industries that follow ISO 8601 standards.