Testing if a date corresponds to a working day with PHP

Published on 2020-10-02 • Modified on 2020-10-02

In this snippet, we will see how to check if a date corresponds to a working day. To do so, we have to use the 'N' (upper case) parameter of the date format function. When using this parameter, Monday returns 1 and Sunday returns 7.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet115Trait
{
    public function snippet115(): void
    {
        $today = new \DateTime();

        echo $today->format('Y-m-d').($this->isWorkingDay($today) ? ' IS a working day.' : ' is NOT a working day.');

        // That's it! 😁
    }

    /**
     * Test if a date is a working day.
     */
    public function isWorkingDay(\DateTimeInterface $date): bool
    {
        return (int) $date->format('N') < 6;
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet115Trait
 */
final class Snippet115Test extends KernelTestCase
{
    /**
     * @return iterable<int, array{0: string, 1: bool}>
     */
    public function provide(): iterable
    {
        yield ['2020-09-28', true];
        yield ['2020-09-29', true];
        yield ['2020-09-30', true];
        yield ['2020-10-01', true];
        yield ['2020-10-02', true];
        yield ['2020-10-03', false];
        yield ['2020-10-04', false];
    }

    /**
     * @dataProvider provide
     *
     * @see Snippet115Trait::snippet115
     */
    public function testSnippet115(string $dateStr, bool $isWorkingDay): void
    {
        self::assertSame($isWorkingDay, $this->isWorkingDay(new \DateTime($dateStr)));
    }

    /**
     * Test if a date is a working day.
     */
    private function isWorkingDay(\DateTimeInterface $date): bool
    {
        return (int) $date->format('N') < 6;
    }
}