Calculer le nombre de jours jusqu'à la fin de l'année avec PHP

Publié le 21/06/2023 • Actualisé le 21/06/2023


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 voyons comment calculer le nombre de jours jusqu'à la fin de l'année avec PHP. PHP calcule correctement le format "z" même si c'est une année bissextile et ajoutera un jour quand c'est nécessaire.


<?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 Snippet262Trait
{
    public function snippet262(): void
    {
        $today = new \DateTime('today');
        $lastDayOfYear = new \DateTime(date('Y-12-31'));
        $daysLeft = (int) $lastDayOfYear->format('z') - (int) $today->format('z');
        $isLeapYear = (bool) $today->format('L');

        echo 'Today: '.$today->format('Y-m-d').PHP_EOL;
        echo $today->format('Y').($isLeapYear ? ' IS' : ' IS NOT').' a leap year.'.PHP_EOL;
        echo "There are $daysLeft day(s) until the end of year! Hurry up! (excluding the current day)";

        // That's it! 😁
    }
}

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

  Travaillez avec moi !

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet262Trait
 */
final class Snippet262Test extends KernelTestCase
{
    /**
     * @return iterable<int, array{0: string, 1: int}>
     */
    public function provideSnippet262(): iterable
    {
        // leap year
        yield ['2020-01-01', 365];
        yield ['2020-02-01', 334];
        yield ['2020-02-28', 307];
        yield ['2020-02-29', 306];
        yield ['2020-03-01', 305];

        // Normal year
        yield ['2023-01-01', 364];
        yield ['2023-02-01', 333];
        yield ['2023-02-28', 306];
        yield ['2023-03-01', 305]; // count since march are identical
    }

    /**
     * @see Snippet262Trait::snippet262
     *
     * @dataProvider provideSnippet262
     */
    public function testSnippet262(string $date, int $expected): void
    {
        $today = new \DateTime($date);
        $lastDayOfYear = new \DateTime(date(sprintf('%s-12-31', $today->format('Y'))));
        $daysLeft = (int) $lastDayOfYear->format('z') - (int) $today->format('z');

        self::assertSame($expected, $daysLeft, 'Wrong count for '.$date);
    }
}