Dateを使用したカレンダーの作成

さて、手軽に楽しめるJavaScript。今度はカレンダーを作ってみた。最初なんで非常に簡単なカレンダーの作成。

main.js

function disp_cal(year) {

	var table = document.createElement('table');
	var tbody = document.createElement('tbody');

	/*
	  カレンダーの表示
	*/
	for(var i=0; i<12; i++) {
		// 月の最終日の取得
		var d = new Date(year, i + 1, 0);
		var tr = document.createElement('tr');
		for(var j=1; j<=d.getDate(); j++) {
			var td = document.createElement('td');
			// 日付の表示
			td.innerHTML = j;
			tr.appendChild(td);
		}
		tbody.appendChild(tr);
	}

	table.appendChild(tbody);
	document.getElementById("result").appendChild(table);
}

function load() {
	document.getElementById("result").innerHTML = "";
	disp_cal(document.frm.elements["box"].value);
}

実行結果

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 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
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 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
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 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
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 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 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
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 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
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

まとめ

うむ。ちゃんと閏年も計算できてますね。