native-dates

サンプル / カレンダー

月間カレンダーグリッド

ロケールに応じた週の境界と DateRange の反復処理を使い、YearMonth から月送りができるカレンダーグリッドを構築します。

試してみよう

  1. 月を前後に送ったあと、Today をクリックして今月に戻ることを確認します。
  2. app.js で configure({ locale: 'de-DE' }) を呼び出し、グリッドが月曜始まりに切り替わることを確認します。
  3. day.isWeekday() で平日のスタイルを変えたり、current.plus(1, 'year') で1年単位の移動を試したりします。
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();

起動中…

仕組み

カレンダーの状態は単一の yearMonth(today()) で管理します。前後の月への移動は、minus() または plus() を1回呼び出すだけです。

月初と月末の前後の空きマスを埋めるため、startOf('week') と endOf('week') で現在のロケールの週の始まりに合わせて日付範囲を広げます。

その範囲に対して every('day') を呼び出すと、すべての日セルが順番に得られます。各セルのクラス付与には day.isToday() と day.isWeekend() をそのまま使えます。