Search code examples
phpdatedatetimemonthcalendar

Calculate Months From two dates


I need to calculate months from two dates

For example :

If date1 = '2014-08-20' means 20th Aug 2014

& date2 = '2014-09-17' means today date

then I need to difference of months = 2 (Aug + September)

Same way

     If `date1 = '2014-03-15'` means 15th March 2014

     &  `date2 =  '2014-09-17'`  means today date

then I need to difference of months = 7 (March + April + May + June + July + Aug + SEPT)

How can I do with php date functions ?


Solution

  • This is what you are looking for?

    $date1 = new DateTime('2014-08-20');
    $date2 = new DateTime('2014-09-17');
    
    echo  $date2->format('n') - $date1->format('n') + 1;