PHP --- DateTimeを利用してカレンダー作成

PHPには標準でカレンダーを作成する機能はないので、実装の一例を紹介します。

二次元配列生成

年月を入力すると、日曜始まりのカレンダー二次元配列が生成されます。(日付が存在しない場所は0が入っています。)

DateTimeのformatに'w'を渡すと曜日(日:0~土:6)が取得でき、't'を渡すとその月の日数が取得できます。

<?php
function getCalendar(int $year, int $month) : array {
    $firstDate = DateTime::createFromFormat('Y-m-d', "{$year}-{$month}-1");
    assert($firstDate);
    $firstDayOfWeek = (int)$firstDate->format('w');
    $lastDay = (int)$firstDate->format('t');
    $weeks = (int)ceil(($firstDayOfWeek + $lastDay) / 7);

    $calender = [];
    for ($i = 0; $i < $weeks * 7; $i++) {
        $day = $i + 1 - $firstDayOfWeek;
        if ($day <= 0 || $lastDay < $day) {
            $day = 0;
        }
        $calender[intdiv($i, 7)][$i % 7] = $day;
    }
    return $calender;
}


Table生成

<table>
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody>
<?php foreach (getCalendar(2018, 6) as $week) { ?>
        <tr>
<?php foreach ($week as $day) { ?>
            <td>
                <?php if (0 < $day) echo $day ?>
            </td>
<?php } ?>
        </tr>
<?php } ?>
    </tbody>
</table>

f:id:any-programming:20180628182608p:plain