Javascriptで万年カレンダーを作る。毎回やり直すので覚え書き。
var calendar = function(year, month) {
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var daysInPrevMonth = daysInMonth[month - 1];
var daysInNextMonth = daysInMonth[month];
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
// カレンダーのHTMLを生成する
var html = "<table>";
html += "<thead><tr><th>日</th><th>月</th><th>火</th><th>水</th><th>木</th><th>金</th><th>土</th></tr></thead>";
html += "<tbody>";
for (var i = 0; i < 6; i++) {
html += "<tr>";
for (var j = 0; j < 7; j++) {
var day = (i * 7) + j + 1;
if (day <= 0 || day > daysInMonth) {
html += "<td></td>";
} else {
var isToday = (day == todayDay && month == todayMonth && year == todayYear);
html += "<td class='" + (isToday ? "today" : "") + "'>" + day + "</td>";
}
}
html += "</tr>";
}
html += "</tbody>";
html += "</table>";
// カレンダーを画面に追加する
var calendarDiv = document.getElementById("calendar");
calendarDiv.innerHTML = html;
};
// カレンダーを初期化する
calendar(2023, 1);
// 月の移動ボタンのイベントハンドラを追加する
var prevMonthButton = document.getElementById("prev-month");
prevMonthButton.addEventListener("click", function() {
var month = calendar.getMonth() - 1;
if (month < 1) {
month = 12;
}
calendar(calendar.getFullYear(), month);
});
var nextMonthButton = document.getElementById("next-month");
nextMonthButton.addEventListener("click", function() {
var month = calendar.getMonth() + 1;
if (month > 12) {
month = 1;
}
calendar(calendar.getFullYear(), month);
});