0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptでカレンダーを3か月分作る

Last updated at Posted at 2022-02-11

javascriptでカレンダーの三か月分を作っていきます。

スクリーンショット 2021-12-08 152429.png

このような形に仕上げていきます。

まずは変数を設定します

  <div id="calendar"></div>

    <script>
      var weeks = ['日', '月', '火', '水', '木', '金', '土'] //weeksには文字列を入れておく
      var date = new Date() //現在の時刻を取得
      var calendarHtml = '' //空を作ってあとからここに追加していく

三か月分for文を回します

      for (var add_month=1; add_month<=3; add_month++) {

次に変数を設定します

        var year = date.getFullYear() //現在の年を取得
        var month = date.getMonth() + add_month; //getMonthは0~11で月を取得する 現在の月から三カ月 
        var startDate = new Date(year, month - 1, 1)//月の最初の日 
        var endDate = new Date(year, month,  0) //月の最後の日 来月の0日目つまり今月の最後の日になる
        var endDayCount = endDate.getDate() //月の最後の日を取り出す 日付の数字を取得する
        var startDay = startDate.getDay() //月の初めの曜日を取得
        var dayCount = 1

ここから表を作っていきます

        calendarHtml += '<table>' //テーブルタグを追加
        calendarHtml += '<caption>' + startDate.getFullYear() + '年' + (startDate.getMonth()+1) + '月' + '</caption>'//カレンダーの年と月の部分
        for (let i = 0; i < weeks.length; i++) { //weeksの数だけつまり曜日の数だけiを回す
            calendarHtml += '<th>' + weeks[i] + '</th>' //曜日を描写する
        }

        for (let w = 0; w < 6; w++) {//週の数は最大6週目まで
            calendarHtml += '<tr>'
  
            for (let d = 0; d < 7; d++) {//dは0から7まで増えていく
                if (w == 0 && d < startDay) {//最初の週でスタートデイ(月の初めの曜日)よりdが小さかったら<td>を増やしていく
                    calendarHtml += '<td></td>'//月の最初の日より前の空白を描写する
                } else if (dayCount > endDayCount) {
                  // 月末日以降は何もしない daycountは月末日まで
                } else {
                    calendarHtml += '<td>' + dayCount + '</td>'//daycountの分だけカレンダーに追加する
                    dayCount++
                }
            }
            calendarHtml += '</tr>'
            if (dayCount > endDayCount) {//daycountがenddaycountを超えると停止する
              break;
            }
        }
        calendarHtml += '</table>'
      }

for分を4回使うことになります

1つ目は3カ月回すためのもの

2つ目は曜日の表を作るためのもの

3つ目は週を月の最後まで回すもの

4つ目は1週間の日にちを最後まで回すためのもの

という形になっています

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?