独習PHP、DateTimeクラスの節、
checkdate関数の紹介の部分で、
カレンダーを表示するサンプルプログラムが、
掲載されていた。
checkdate.php
<?php function calendar($year, $month) { for ($i = 1; $i < 32; $i++) { if (checkdate($month, $i, $year)) { print "{$i} "; } } } print "2016年2月のカレンダー:<br />"; calendar(2016, 2);
これだと、日付を1列に表示するだけなので、
カレンダーっぽい並びに表示するよう、
アレンジしてみた。
calendar.php
<?php $year = 2017; $month = 8; print "{$year}年{$month}月のカレンダー:<br />\n"; calendar($year, $month); function calendar($year, $month) { // 表示位置を揃えるためにテーブルを使う print "<table><tr>\n"; // 1日以前のところは空欄にする $dt1st = new DateTime($year.'/'.$month.'/1 10:58:31'); for ($i = 0; $i < $dt1st->format('w'); $i++){ print "<td></td>\n"; } // 日付を順番に表に挿入していく for ($i = 1; $i < 32; $i++) { if (checkdate($month, $i, $year)) { $dt = new DateTime($year.'/'.$month.'/'.$i.' 10:58:31'); $weekday = $dt->format('w'); switch($weekday){ case 0 : $color = "#FF0000"; break; // 日曜日は赤字 case 6 : $color = "#0000FF"; break; // 土曜日は青字 default : $color = "#000000"; break; // 平日は黒字 } print "<td align='center' style=\"color:{$color}\">{$i}</td>\n"; // 土曜日までいったら次の行へ if ($weekday == 6){ print "</tr>\n<tr>\n"; }; } } print "</tr></table>"; }
祝日を赤字にする方法はご容赦をw
DateTimeオブジェクトのformatメソッド、
‘w’記述子を指定してあげると曜日が返ってくる。
(0:日曜日~6:土曜日まで。)
他にも曜日を返す記述子は、
D:Mon~Sun
I:Monday~Sunday
N:1(月曜日)~7(日曜日)
がある。
参考書籍:
![]() |
新品価格 |