Tester si une date correspond à un jour ouvrable avec PHP

Publié le 02/10/2020 • Actualisé le 02/10/2020


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous allons voir comment vérifier si une date donnée correspond à un jour ouvrable ou pas. Pour ce faire, nous devons utiliser le paramètre 'N' (en majuscule) de la fonction date_format. Quand on utilise ce paramètre, lundi retourne 1 et dimanche retourne 7.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
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;
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !

<?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;
    }
}