-1

How to find number of months between two dates using PHP? and provide dates also like below

$fromdate = 12-01-2018
$todate = 18-04-2018

i want output per month like

12-01-2018 - 12-02-2018
12-02-2018 - 12-03-2018
12-03-2018 - 12-04-2018
12-04-2018 - 18-04-2018

i tried

    $datetime1 = new DateTime("2010-06-20");

    $datetime2 = new DateTime("2011-06-22");

    $difference = $datetime1->diff($datetime2);

    echo 'Difference: '.$difference->y.' years, '
        .$difference->m.' months, '
        .$difference->d.' days<br>';

    print_r($difference);
Rahul Tathod
  • 348
  • 5
  • 12

1 Answers1

1

You could use this code. It increments $start (=$fromdate) by a month until it is equal to or later than $end (=$todate).

$fromdate = '12-01-2018';
$todate = '18-04-2018';

$start = DateTime::createFromFormat('d-m-Y', $fromdate);
$end = DateTime::createFromFormat('d-m-Y', $todate);

do {
    echo $start->format('d-m-Y') . ' - ';
    $start->add(new DateInterval('P1M'));
    if ($start >= $end) {
        echo $end->format('d-m-Y') . "\n";
        break;
    }
    echo $start->format('d-m-Y') . "\n";
} while (true)

Output:

12-01-2018 - 12-02-2018
12-02-2018 - 12-03-2018
12-03-2018 - 12-04-2018
12-04-2018 - 18-04-2018
Nick
  • 138,499
  • 22
  • 57
  • 95