native-dates

Examples / Calendars

A month grid

Build a navigable calendar month grid from a YearMonth using locale-aware week boundaries and DateRange iteration.

Try this

  1. Step backward and forward through months, then click Today to jump back to the current month.
  2. Call configure({ locale: 'de-DE' }) in app.js to shift the grid to Monday-first weeks.
  3. Style weekdays with day.isWeekday() or step a full year with current.plus(1, 'year').
import { today, weekdayNames, yearMonth } from 'native-dates';

const heading = document.querySelector('#month');
const header = document.querySelector('#weekdays');
const cells = document.querySelector('#days');

let current = yearMonth(today());

header.innerHTML = weekdayNames('short').map((name) => `<span>${name}</span>`).join('');

function render() {
  heading.textContent = current.format('long');
  const grid = current.start.startOf('week').to(current.end.endOf('week'));

  cells.innerHTML = grid.every('day').map((day) => {
    const classes = [
      day.month !== current.month ? 'outside' : '',
      day.isWeekend() ? 'weekend' : '',
      day.isToday() ? 'today' : '',
    ].filter(Boolean).join(' ');
    return `<span class="${classes}">${day.day}</span>`;
  }).join('');
}

document.querySelector('#prev').addEventListener('click', () => {
  current = current.minus(1, 'month');
  render();
});
document.querySelector('#today').addEventListener('click', () => {
  current = yearMonth(today());
  render();
});
document.querySelector('#next').addEventListener('click', () => {
  current = current.plus(1, 'month');
  render();
});

render();

Starting…

How it works

The calendar state is a single yearMonth(today()) value. Stepping between months takes one call to minus() or plus().

To fill leading and trailing week cells, startOf('week') and endOf('week') expand the month’s bounds to match the active locale’s first day of the week.

Calling every('day') on that range returns every day cell in order, where day.isToday() and day.isWeekend() drive the cell classes directly.