Check the difference between two dates in months

Asked

Viewed 2,154 times

4

Guys I need to put together a code on php where I enter 2 dates and it returns the difference in months. Example:

 $data1 = "2016-03-01";
 $data2 = "2016-06-10";

 Resultado 3 meses

Example 2:

 $data1 = "2015-06-01";
 $data2 = "2016-06-10";

 Resultado 12 meses

Solved as follows: $monthsAhead = $range->m + ($range->y * 12);

  • 2

    not and not duplicated, that’s a very different situation.

  • But you can use the same answer as the previous question, because both calculate

  • @Hugoborges This is it -> $intervalo = $firstDate->diff($lastDate);

  • I posted a solution

  • eu Tenez thus: $dateInterval = $data_inicio->diff($data_fim); echo $dateInterval->m; however it ignores the year, ie if I put '2016-06-01' and 2015-06-01' it returns me 0, and the correct would be 12

  • @Hugoborges do not put the answer to the question. Add your own answer in the answers section ;)

Show 1 more comment

1 answer

3

You can do it this way:

$data1 = new DateTime( '2013-12-11' );
$data2 = new DateTime( '1994-04-17' );

$intervalo = $data1->diff( $data2 );

echo "Intervalo é de {$intervalo->y} anos, {$intervalo->m} meses e {$intervalo->d} dias"; 
  • 1

    if I put '2016-06-01' and 2015-06-01' it returns me 0, the correct one would be 12

  • 3

    solved thus $monthsAhead = $interval->m + ($interval->y * 12);

  • @Good hugoborges!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.