※この記事は「2021年4月20日」に更新しました。
PHP でカレンダーを作成します。
前回の続きです。
今回は、指定した月のカレンダーを表示できるようにしていきたいと思います。

カレンダーを作成する
カレンダーを作成します。
今回の記事のポイントは、以下の通りです。
- 指定した月のカレンダーを表示させる
前回のコードを修正していきます。
指定した月のカレンダーを表示させる
それでは、指定した月のカレンダーを表示させていきます。
指定月を格納させる変数を用意して、それに対して、インスタンスを生成するという準備を行います。
$t = '2019-11';
$thisMonth = new DateTime($t);
$yearMonth = $thisMonth->format('F Y');
thisMonth は、指定した月のインスタンスを格納するための変数です。
yearMonth は、指定した月の年月を表しています(文字列型)。
実際に echo などで表示させてみると以下のようになるかと思います。
November 2019
あとは、この yearMonth を使って、前回のコードを修正していきます。
例えば、前回だと以下のような表現があったかと思います。
$daterange = new DatePeriod(
new DateTime('first day of this month'),
new DateInterval('P1D'),
new DateTime('first day of next month')
);
this month は、yearMonth に書き換えることができます。
'first day of ' . $yearMonth
next month は、以下のように表現することができます。
$yearMonth . ' +1 month'
そして、prevous month は、以下のように表現できます。
$yearMonth . ' -1 month'
これらを使って、書き換えていき、あとは HTML で表示させているカレンダーのタイトル部分も yearMonth を使うようにします。
サンプルコード【PHP】
サンプルコードです(PHP)。
スタイルシートに関しては、今回も変更していないので、第1回目のものをご参照ください。
<?php
$t = '2019-11';
$thisMonth = new DateTime($t);
$yearMonth = $thisMonth->format('F Y');
$tail = '';
$PreMonthDay = new DateTime('last day of ' . $yearMonth . ' -1 month');
while ($PreMonthDay->format('w') < 6) {
$tail = sprintf('<td class="except">%d</td>', $PreMonthDay->format('d')) . $tail;
$PreMonthDay->sub(new DateInterval('P1D'));
}
$content = '';
$daterange = new DatePeriod(
new DateTime('first day of ' . $yearMonth),
new DateInterval('P1D'),
new DateTime('first day of ' . $yearMonth . ' +1 month')
);
foreach ($daterange as $day) {
if ($day->format('w') % 7 === 0) {
$content .= '</tr><tr>';
}
$content .= sprintf('<td class="week_%d">%d</td>', $day->format('w'), $day->format('d'));
}
$head = '';
$nextMonthDay = new DateTime('first day of ' . $yearMonth . ' +1 month');
while ($nextMonthDay->format('w') > 0) {
$head .= sprintf('<td class="except">%d</td>', $nextMonthDay->format('d'));
$nextMonthDay->add(new DateInterval('P1D'));
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>My Calendar</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<table>
<thead>
<tr>
<th><a href="">«</a></th>
<th colspan="5"><?php echo $yearMonth; ?></th>
<th><a href="">»</a></th>
</tr>
</thead>
<tbody>
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr>
<tr>
<?php echo $tail . $content . $head; ?>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="7"><a href="">Today</a></th>
</tr>
</tfoot>
</table>
</body>
結果は、以下の通りです。
最後に
いかがでしょうか。
次回は、リンクを動作させるための準備をしていく予定です。
コツコツとやっていきましょう。

