Getting a PHP DateTime object for the last day of the month

Published on 2021-01-30 • Modified on 2021-01-30

This one is for me! I always want to write: "last day of the month" which sounds OK... but, it's not! It's "last day of this month"! Perhaps a day I will remember. Until this date, I've got this snippet to remind me now. Note that the string isn't case sensitive, using an uppercase "THIS" works. I have also discovered while writing this snippet that using "last day of" works too! 😮


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet132Trait.php

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 Snippet132Trait
{
    public function snippet132(): void
    {
        $lastDayOf = new \DateTime('last day of');
        $lastDayOfThisMonth = new \DateTime('last day of this month');

        var_dump($lastDayOf);
        var_dump($lastDayOfThisMonth); // That's it! 😁
    }
}

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

<?php

declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet132Trait
 */
final class Snippet132Test extends KernelTestCase
{
    /**
     * @covers Snippet132Trait::snippet132
     */
    public function testSnippet132isNotOk(): void
    {
        $this->expectException(\Exception::class);
        new \DateTime('last day of the month');
    }

    /**
     * @covers Snippet132Trait::snippet132
     */
    public function testSnippet132isOk(): void
    {
        $date = new \DateTime('2021-01-12');
        $date->modify('last day of this month');

        $date2 = new \DateTime('2021-01-15');
        $date2->modify('last day of');

        self::assertSame('2021-01-31', $date->format('Y-m-d'));
        self::assertSame($date2->format('Y-m-d'), $date2->format('Y-m-d'));
    }
}