0

Possible Duplicate:
Find Month difference in php?

say, i have 2012-03-01 and 2013-02-01 saved in database. When calculating number of months in between, i want to get 12 months instead of exact number of days or exact number of months (e.g 11.92 months) How to do it in php?

Community
  • 1
  • 1
Mario
  • 855
  • 4
  • 19
  • 30

2 Answers2

2

DateTime make this easy (requires PHP 5.3 or greater)

$datetime1 = new DateTime('2012-03-01');
$datetime2 = new DateTime('2013-02-01');
$interval = $datetime2->diff($datetime1);
echo (($interval->format('%y') * 12) + $interval->format('%m'));
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Looks like [this](http://stackoverflow.com/a/2681841/679449) answer. Perhaps OP should use a search? – Kermit Jan 31 '13 at 19:19
  • 1
    this is wrong. this ignores years. you have to do `(($interval->format('%y') * 12) + $interval->format('%m'))` – gondo Mar 20 '15 at 21:22
1

Try this:

<?php
$d1 = date_create('2013-01-31');
$d2= date_create('2013-05-12');
$interval= date_diff($d1, $d2);
echo $interval->format('%m months');
?>
Niels
  • 48,601
  • 4
  • 62
  • 81