LoginSignup
1

More than 5 years have passed since last update.

PHPで土日祝日の一覧を出力する

Last updated at Posted at 2019-02-18

土日と祝日だけを取得したくて、書いてみました。
祝日はYasumiで確認します。
土日はCarbon使うことも出来ますが、曜日を見て判断しています。

準備

console
% composer require azuyalabs/yasumi

コード

holiday.php
<?php
declare(strict_types=1);
require_once 'vendor/autoload.php';

/**
 * 土日祝日ジェネレータ
 *
 * @param int $year 範囲の年
 * @param string $start 開始年月日(Y-m-d)
 * @param string $end 終了年月日(Y-m-d)
 * @param string $format 出力フォーマット
 * @return Generator
 * @throws ReflectionException
 */
function getStaticHoliday(int $year, string $start, string $end, string $format = 'Y-m-d'): Generator
{
    try {
        $startObj = new \DateTimeImmutable($start . 'T00:00');
        $endObj = new \DateTimeImmutable($end . 'T24:00');
        $interval = new \DateInterval('P1D');
        $period = new \DatePeriod($startObj, $interval, $endObj);
    }catch (Exception $e) {
        echo $e->getMessage(), PHP_EOL;
        return;
    }

    $holidays = \Yasumi\Yasumi::create('Japan', $year, 'ja_JP');

    foreach ($period as $day) {
        // 休日または土日である場合
        if ($holidays->isHoliday($day) || false !== array_search($day->format('w'), [0, 6])) {
            yield $day->format($format);
        }
    }
}

try {
    foreach (getStaticHoliday(2019, '2019-02-18', '2019-08-01', 'Y/m/d') as $holiday) {
        echo $holiday, PHP_EOL;
    }
} catch (ReflectionException $e) {
    echo $e->getMessage(), PHP_EOL;
}

出力結果

coneole
% php holiday.php
2019/02/23
2019/02/24
2019/03/02
2019/03/03
2019/03/09
2019/03/10
2019/03/16
2019/03/17
2019/03/21
...

参考

【PHP】日本の祝日を扱うときは「Yasumi」を使ってみてはどうですか
【PHP】日付を一日ずつ進めて表示させてゆく(コメントより)

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
1