Calendar Week Developer Guide & API
How to implement ISO 8601 calendar weeks programmatically.
Calculating calendar weeks programmatically can be surprisingly complex due to the rules of ISO 8601 (where Week 1 is defined by the first Thursday of the year). Many native date libraries default to US-centric (Sunday start) weeks, causing bugs that only appear in early January.
Below are the most robust ways to calculate calendar weeks across various languages and databases.
JavaScript & TypeScript
Native JavaScript's Date object does not have a built-in method for retrieving the ISO week number. You can either write a custom math function or use a robust library.
Native JS Date Math
function getISOWeek(date) {
const target = new Date(date.valueOf());
const dayNr = (date.getDay() + 6) % 7;
target.setDate(target.getDate() - dayNr + 3);
const firstThursday = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - target) / 604800000);
}Using date-fns
If you use date-fns, simply use the built-in ISO functions:
import { getISOWeek, getISOWeekYear } from 'date-fns';
const date = new Date('2026-01-01');
const week = getISOWeek(date); // 1
const year = getISOWeekYear(date); // 2026Using dayjs
For dayjs, you must extend it with the isoWeek plugin:
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
dayjs.extend(isoWeek);
const week = dayjs('2026-01-01').isoWeek();Backend Implementations
Python
Python's datetime module has excellent native support for ISO calendars.
import datetime d = datetime.date(2026, 1, 1) year, week, weekday = d.isocalendar() # Returns: (2026, 1, 4)
PHP
PHP's native date() function supports the W format character for ISO-8601 week numbers.
$date = new DateTime('2026-01-01');
$week = $date->format("W"); // "01"
$isoYear = $date->format("o"); // "2026"Database Queries (SQL)
Aggregating data by week is incredibly common in reporting and analytics.
PostgreSQL
PostgreSQL fully supports ISO weeks via EXTRACT or TO_CHAR.
-- Get integer week SELECT EXTRACT(WEEK FROM timestamp '2026-01-01'); -- Get formatted string (e.g., '26-W01') SELECT TO_CHAR(timestamp '2026-01-01', 'YY-"W"IW');
MySQL
In MySQL, the WEEK() function requires a mode argument. Mode 3 specifies ISO 8601 rules (Monday start, Week 1 has 4+ days).
SELECT WEEK('2026-01-01', 3);Free Embeddable Widget
If you are building an internal dashboard (like in Notion, Confluence, or a custom React app) and simply want a tool for users to calculate week numbers visually, you don't need to build it yourself.
Developer Tool
We provide a free, zero-dependency, privacy-first Calendar Week Embed Widget. Drop our lightweight iframe into your application to instantly give your users a localized ISO/US week calculator.
Was this article helpful?
Your feedback helps us improve our guides.