- PHP

Find how many months are between two dates in PHP

To find how many months are between the dates in PHP, use the combination of DateTime(), diff(), and format() functions.

Example:

Count the number of months between two dates in PHP.

<?php
    $firstDate = new DateTime("2021-07-20");
    $secondDate = new DateTime("2022-05-25");

    $monthsBetween = $secondDate->diff($firstDate)->format("%m months");

    echo $monthsBetween;
?>

Output: 10 months

Example 2:

Count the number of months and days between two dates in PHP.

<?php
    $firstDate = new DateTime("2021-07-20");
    $secondDate = new DateTime("2022-05-25");

    $monthsBetween = $secondDate->diff($firstDate)->format("%m months %d days");

    echo $monthsBetween;
?>

Output: 10 months 5 days

Months between dates function in PHP

If you want to use the pre-built function, you can use something like this:

<?php
    function monthsBetweenDates($date1, $date2, $format) {
        $firstDate = new DateTime($date1);
        $secondDate = new DateTime($date2);

        return $secondDate->diff($firstDate)->format($format);
    }

    // Examples:
    
    echo monthsBetweenDates("02.06.2015", "25.12.2015", "%m months"); // Output: 6 months
    echo monthsBetweenDates("02.06.2015", "25.12.2015", "%m months and %d days"); // Output: 6 months and 23 days
?>