Calculating the number of months between two dates in PHP

Published on 2022-06-15 • Modified on 2022-06-15

In this snippet, we see how to calculate the number of months between two dates in PHP. Here, we don't care about the days at all. For example, this is useful to check when a credit card expires or if it is about to expire (a credit card is valid until the last day of its expiration date). The first example uses raw PHP, and the second uses the Carbon date library. It can be tricky to do calculations on dates; I generally prefer relying on an existing library, and as you can see, the code is also much more concise.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Carbon\Carbon;

/**
 * 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 Snippet204Trait
{
    public function snippet204(): void
    {
        // PHP
        $date1 = new \DateTime('2022-06-15');
        $date2 = new \DateTime('2022-07-01');
        $date3 = new \DateTime('now');

        $year1 = (int) $date1->format('Y');
        $year2 = (int) $date2->format('Y');
        $year3 = (int) $date3->format('Y');

        $month1 = (int) $date1->format('m');
        $month2 = (int) $date2->format('m');
        $month3 = (int) $date3->format('m');

        $diff2 = (($year2 - $year1) * 12) + ($month2 - $month1);
        $diff3 = (($year3 - $year1) * 12) + ($month3 - $month1);
        echo \sprintf('Diff in month from %s to %s: ', $date1->format('Y-m'), $date2->format('Y-m')).$diff2.PHP_EOL;
        echo \sprintf('Diff in month from %s to now: ', $date1->format('Y-m')).$diff3.PHP_EOL.PHP_EOL;

        // Carbon
        $date4 = new Carbon('2022-06-15');
        $date5 = new Carbon('2022-07-01');
        $date6 = Carbon::now();
        $diff5 = (($date5->year - $date4->year) * 12) + ($date5->month - $date4->month);
        $diff6 = (($date6->year - $date4->year) * 12) + ($date6->month - $date4->month);
        echo \sprintf('Diff in month from %s to %s: ', $date4->format('Y-m'), $date5->format('Y-m')).$diff5.PHP_EOL;
        echo \sprintf('Diff in month from %s to now: ', $date4->format('Y-m')).$diff6.PHP_EOL;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!