2

I need to work out the number of months between a date like this:

$inputDate = '09/08/2016';

that is entered in the MM/DD/YYYY format, and the current date, e.g.:

$today = date("m/d/Y");

I've been looking at the date_diff but can't seem to get the syntax right here and appreciate any help here.

user982124
  • 4,416
  • 16
  • 65
  • 140

1 Answers1

2

You can use DateTime and diff

$datetime1 = new DateTime();
$datetime2 = new DateTime('09/08/2016');
$interval = $datetime1->diff($datetime2);
$months = $interval->format('%m months'); # you can also use %a days %h hours %i minutes %s seconds
echo $months;
# 8 months
# optimally you can use:  
# echo $datetime1->diff($datetime2)->y*12;
# or 
# echo $interval->m


Update based-on comments:

$datetime1 = new DateTime();
$datetime2 = new DateTime('09/08/2015');
$interval = $datetime1->diff($datetime2);
echo  (($interval->format('%y') * 12) + $interval->format('%m')) . " full months difference";

Note:

A DateInterval Object looks like:

DateInterval Object
(
    [y] => 3
    [m] => 5
    [d] => 15
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 1264
)

That's why we've to multiply the number of years * 12 and add the months in order to get the difference in months. Strange, but this is how it works...

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • I just tested this with a date of '05/13/2015' and it's returning 0 months - any idea why this is happening? – user982124 May 18 '17 at 00:37
  • I've no idea why it's returning 0 months, although, you can also get the difference in months using `$datetime1->diff($datetime2)->y*12;` – Pedro Lobito May 18 '17 at 00:54
  • I noticed if you change the year on the $datetime2 to 2015 ('$datetime2 = new DateTime('09/08/2015');') it still returns 8 months. – user982124 May 18 '17 at 00:55
  • I'm still looking into this, it's a mystery to me! – Pedro Lobito May 18 '17 at 01:06
  • I'm wondering whether this takes into account the years, or only works when the 2 dates are in the same year or less than 12 months? – user982124 May 18 '17 at 01:08
  • I think the most reliable way to get the correct results is using : `echo (($interval->format('%y') * 12) + $interval->format('%m')) . " full months difference";`, I'll update the answer. Grabbed from http://stackoverflow.com/a/2681841/797495 – Pedro Lobito May 18 '17 at 01:16
  • This appears to be an issue when the interval is greater than 13 months - see here for a solution http://stackoverflow.com/questions/10427694/php-difference-in-months-between-two-dates (use $interval->m + 12*$interval->y to fix this) – user982124 May 18 '17 at 01:21
  • I've updated my answer with an explanation. GL @user982124 – Pedro Lobito May 18 '17 at 01:42