0

I wanted to calculate the month difference between two yyyymm dates. I have this function below, however it only works if I use yyyy-mm instead.

$date1 = new DateTime('2014-01');
$date2 = new DateTime('2013-06');
$mth = mthdiff($date1, $date2);

function mthdiff($date1,$date2){


$diff = $date1->diff($date2);

return (($diff->format('%y') * 12) + $diff->format('%m'));

}
user3543512
  • 133
  • 1
  • 1
  • 13

1 Answers1

3

Modify your function to use DateTime::createFromFormat():

function mthdiff($date1,$date2){
    $d1 = DateTime::createFromFormat('Ym', $date1);
    $d2 = DateTime::createFromFormat('Ym', $date2);
    $diff = $d1->diff($d2);
    return (($diff->format('%y') * 12) + $diff->format('%m'));
}

Usage:

echo mthdiff('201401', '201306');

Output:

7

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150