JavaScript:カレンダーの作成

JavaScript で作成した超簡易カレンダーです。

“<”、“>”をクリックすると、月が変わります。

 

 

プログラムは以下のようになります。

calendar.htm

<html>
<body>
<div id="calendar"></div>
<script src="./calendar.js"></script>
<script>calendar("calendar")</script>
</body>
</html>
 

 

calendar.js

var $date = new Date();
var $year = $date.getFullYear();
var $month = $date.getMonth();

function calendar(id) {
  $id = id;
  var first = new Date($year, $month, 1);
  var last = new Date($year, $month + 1, 0);
  var first_day = first.getDay();
  var last_date = last.getDate();
  var flag = true;
  var counter = 1;
  var calendar = "<table border='1'>";
  calendar += "<caption>"
  calendar += "<strong onclick='decrease()'>&lt; </strong>"
  calendar += $year + "/" + ("00" + ($month + 1)).slice(-2)
  calendar += "<strong onclick='increase()'> &gt;</strong>"
  calendar += "</caption>";
  var week = ["日", "月", "火", "水", "木", "金", "土"];
  for (var j = 0; j < 7; j++) {
    calendar += "<th>" + week[j] + "</th>";
  }
  for (var i = 0; i < 6; i++) {
    calendar += "<tr align='center'>";
    for (var j = 0; j < 7; j++) {
      if (i == 0 && first_day == j) flag = false;
      if (counter > last_date) flag = true;
      calendar += "<td>";
      calendar += flag ? "&nbsp;" : counter++;
      calendar += "</td>";
    }
    calendar += "</tr>";
    if (counter > last_date) break;
  }
  calendar += "</table>";
  document.getElementById(id).innerHTML = calendar;
}

function decrease() {
  if ($month-- == 0) {
    $year--;
    $month = 11;
  }
  calendar($id);
}

function increase() {
  if ($month++ == 11) {
    $year++;
    $month = 0;
  }
  calendar($id);
}
 

 


参考サイト