カレンダーでいう前月の部分(Tail)を作るロジックです。Last day of ~ -1 monthとなっているのでまず初めに前月の最終日を取得しています。subで1日ずつ前日に遡り、日曜日になるまでループし、文字色をグレーにするスタイルを定義しています。
$tail = '';
$lastDayOfPrevMonth = new DateTime('last day of ' . $yearMonth . ' -1 month');
while ($lastDayOfPrevMonth->format('w')<6){
$tail = sprintf('<td class="gray">%d</td>', $lastDayOfPrevMonth->format('d')) . $tail;
$lastDayOfPrevMonth->sub(new DateInterval('P1D'));
}
翌月の部分(head)の部分は逆にfast day of ~ +1 monthで取得しaddで1日ずつ翌日に進み土曜日までループして取得します。
$head='';
$firstDayOfNextMonth = new DateTime('first day of ' . $yearMonth . ' +1 month');
while ($firstDayOfNextMonth->format('w')>0){
$head .= sprintf('<td class="gray">%d</td>', $firstDayOfNextMonth->format('d'));
$firstDayOfNextMonth->add(new DateInterval('P1D'));
}
次にメインとなる当月の部分ですが、初めにDatePeriodクラスを使い$thisMonthの1日から翌月1日まで1日間隔の日付データ$periodを作成します。
foreach文で$periodを1日ずつ取り出し、日曜と土曜に色を付けるスタイルを指定し、日曜日の場合はHTMLタグの<tr>を指定してテーブルを形成しています。
$body = '';
$period = new DatePeriod(
new DateTime('first day of ' . $yearMonth),
new DateInterval('P1D'),
new DateTime('first day of ' . $yearMonth . ' +1 month')
);
$today = new DateTime('today');
foreach($period as $day){
if ($day->format('w') % 7 === 0){ $body .= '</tr><tr>';}
$todayClass = ($day->format('Y-m-d') === $today->format('Y-m-d')) ? 'today' : '';
$body .= sprintf('<td class="youbi_%d %s">%d</td>', $day->format('w'), $todayClass, $day->format('d'));
}
このカレンダーアプリを作成するとPHPの日付操作を大体理解できると思います。非常にシンプルなので一度作ってみてはいかがですか。
コメント