Print a monthly calendar in JavaScript
Advanced · 4 min read
Date pickers, booking pages and wall calendars all show a month the same way: seven columns for the days of the week, and the dates filling rows from left to right. The tricky part is the start. A month rarely begins on a Monday, so the first row needs some blank cells.
In this tutorial you will print January 2026 as a text calendar, Monday first, with every line the same width. The method works for any month and turns straight into an HTML grid later. You need to know arrays, loops and padStart. The day-of-week maths is explained below.
What January 2026 should look like
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
1 January 2026 is a Thursday, so the first row starts with three blank cells: Monday, Tuesday and Wednesday. Each cell is two characters wide, and cells are separated by one space.
Monday-first day numbers
getDay() numbers the days from Sunday: 0 is Sunday, 1 is Monday, up to 6 for Saturday. For a Monday-first calendar we want Monday to be 0 and Sunday 6. (getDay() + 6) % 7 does that:
const first = new Date(2026, 0, 1);
console.log(first.getDay()); // 4: Thursday, counting from Sunday
console.log((first.getDay() + 6) % 7); // 3: Thursday, counting from Monday
Adding 6 and taking the remainder after dividing by 7 moves every day back one place, and Sunday (0) wraps round to 6. The answer, 3, is also the number of blank cells before the 1st. We call it the lead.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
134 A month laid out as a calendar
hardPrint one month as a grid of weeks, Monday first, with the day numbers right-aligned in two characters. January 2026 starts on a Thursday, so the first row needs three blank cells. Every line must come out the same width.
Stuck? Three hints, smallest first
- 1.
getDay()is Sunday-first, so(getDay() + 6) % 7gives the number of blanks before the 1st. - 2. Build one flat list of cells: the blanks, then the day numbers, then blanks to fill the last week.
- 3. Slice the flat list into sevens, and pad each cell with
padStart(2).
Step 1: find the lead and the number of days
const year = 2026;
const month = 0; // January: months count from 0
const lead = (new Date(year, month, 1).getDay() + 6) % 7;
const days = new Date(year, month + 1, 0).getDate();
console.log(lead, days); // 3 31
new Date(year, month + 1, 0) is day 0 of the next month, which JavaScript reads as the last day of this month. Its getDate() is the month's length.
Step 2: one flat list of cells
Here's the trick that keeps this simple: don't think in rows yet. Build a single list of all the cells, in order: the blanks, then the days, then more blanks until the list is a multiple of 7.
const lead = 3;
const days = 31;
const cells = [];
for (let i = 0; i < lead; i++) cells.push(''); // before the 1st
for (let d = 1; d <= days; d++) cells.push(String(d));
while (cells.length % 7 !== 0) cells.push(''); // after the last day
console.log(cells.length); // 35
console.log(cells.slice(0, 5)); // [ '', '', '', '1', '2' ]
3 blanks plus 31 days is 34 cells. The while loop adds one more blank to reach 35, which is exactly five weeks. cells.length % 7 is 0 when the count divides evenly by 7.
The blanks at the end matter: without them the last row would be short, and the lines would have different widths.
Step 3: cut the list into weeks
Now slice off seven cells at a time. Pad each cell to two characters with padStart(2), so '1' becomes ' 1' and the digits line up on the right. Then join them with a space:
const HEADER = 'Mo Tu We Th Fr Sa Su';
function monthGrid(year, month) {
const first = new Date(year, month, 1);
const lead = (first.getDay() + 6) % 7;
const days = new Date(year, month + 1, 0).getDate();
const cells = [];
for (let i = 0; i < lead; i++) cells.push('');
for (let d = 1; d <= days; d++) cells.push(String(d));
while (cells.length % 7 !== 0) cells.push('');
const weeks = [];
for (let i = 0; i < cells.length; i += 7) {
weeks.push(cells.slice(i, i + 7).map((c) => c.padStart(2)).join(' '));
}
return { lead, days, weeks };
}
const january = monthGrid(2026, 0);
console.log(HEADER);
for (const week of january.weeks) console.log(week);
console.log([...new Set([HEADER, ...january.weeks].map((l) => l.length))]); // [ 20 ]
The loop counts up in sevens: i is 0, 7, 14, 21, 28. slice(i, i + 7) takes one week each time. An empty cell pads to two spaces, so blank days take up the same room as real ones.
The last line puts every line's length into a Set, which keeps only distinct values. One value, 20, proves every line, header included, is the same width. (The last week ends in three spaces, so it's 20 characters even though they're invisible.)
Step 4: not every month has five rows
function rows(year, month) {
const lead = (new Date(year, month, 1).getDay() + 6) % 7;
const days = new Date(year, month + 1, 0).getDate();
return Math.ceil((lead + days) / 7);
}
console.log(rows(2026, 0)); // 5: January 2026
console.log(rows(2027, 1)); // 4: February 2027 starts on a Monday
console.log(rows(2026, 7)); // 6: August 2026 starts on a Saturday
A 28-day February that starts on a Monday fits in exactly four rows. A 31-day month that starts on a Saturday needs six. A layout that always reserves five rows will cut off the last week now and then. Building the list and slicing it, as above, gives the right number of rows every time.
The full solution
The answer panel has monthGrid, returning the lead, the day count and the weeks, and prints January 2026 under the header. The checks cover the lead, the padded last row, the equal widths, and the four-row and six-row months. Press Run to see the output.
const HEADER = 'Mo Tu We Th Fr Sa Su';
function monthGrid(year, month) {
const first = new Date(year, month, 1);
const lead = (first.getDay() + 6) % 7; // Monday-first offset
const days = new Date(year, month + 1, 0).getDate();
const cells = [];
for (let i = 0; i < lead; i++) cells.push(''); // before the 1st
for (let d = 1; d <= days; d++) cells.push(String(d));
while (cells.length % 7 !== 0) cells.push(''); // after the last day
const weeks = [];
for (let i = 0; i < cells.length; i += 7) {
weeks.push(cells.slice(i, i + 7).map((c) => c.padStart(2)).join(' '));
}
return { lead, days, weeks };
}
const january = monthGrid(2026, 0);
console.log(HEADER);
for (const week of january.weeks) console.log(week);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('1 January 2026 is a Thursday, which is three cells in', [new Date(2026, 0, 1).getDay(), january.lead], [4, 3]);
test('a Sunday-first grid would have needed four', (new Date(2026, 0, 1).getDay() + 7) % 7, 4);
test('the month needs five rows', january.weeks.length, 5);
test('the first row is blank until the 1st', [january.weeks[0].trimStart(), january.weeks[0].indexOf('1')], ['1 2 3 4', 10]);
test('the last row is padded out rather than left short', january.weeks[4], '26 27 28 29 30 31 ');
test('so every line, header included, is exactly the same width', [...new Set([HEADER, ...january.weeks].map((l) => l.length))], [20]);
test('February 2026 starts on a Sunday, the widest possible lead', monthGrid(2026, 1).lead, 6);
test('February 2027 starts on a Monday and has 28 days, so it fits in four rows', [monthGrid(2027, 1).lead, monthGrid(2027, 1).weeks.length], [0, 4]);
test('and a 31-day month starting on a Saturday needs six', [monthGrid(2026, 7).lead, monthGrid(2026, 7).days, monthGrid(2026, 7).weeks.length], [5, 31, 6]);
The trick that makes this simple is refusing to think in rows. Build one flat list — blanks, then days, then blanks — and only slice it into weeks at the end. Trying to decide, inside a nested loop, whether cell (row, column) holds a day is where the off-by-one errors live.
(getDay() + 6) % 7 is the Monday-first conversion, and it is worth understanding rather than memorising: it rotates Sunday from 0 to 6 and pulls everything else down one. Nigerian calendars are usually Monday-first, US ones Sunday-first, and the difference is exactly this one expression — the second assertion shows the same date needing a different lead under each convention.
The row count is not fixed. Five is normal, four happens only for a non-leap February beginning on a Monday, and six is needed whenever the lead plus the day count passes 35 — a 31-day month starting Saturday or Sunday. A layout that assumes five rows will clip a week roughly twice a year, which the last two assertions pin down.
Common mistakes
- Using
getDay()directly for a Monday-first grid. It counts from Sunday, so everything shifts one column. Convert with(getDay() + 6) % 7. - Not padding the last week. The last line comes out shorter than the others.
- Assuming five rows. Some months need four and some need six.
Try it yourself
- Make a Sunday-first version with the header
Su Mo Tu We Th Fr Sa. Which part of the code changes? - Mark today's date by wrapping it in brackets, like
[15]. Keep the lines the same width. - Print all twelve months of 2026, each with its name centered above it.