简体   繁体   中英

Calculating years/months/days between dates

$date1 = "2000-01-01";
$date2 = "2011-03-14";

$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365 * 60 * 60 * 24));
$months = ceil(($diff - ($years * 365 * 60 * 60 * 24)) / ((365 * 60 * 60 * 24) / 12));
$months2 = floor(($diff - ($years * 365 * 60 * 60 * 24)) / ((365 * 60 * 60 * 24) / 12));
$days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months2 * 30 * 60 * 60 * 24)/ (60 * 60 * 24));

The answer I get is 11 years , 2 months and 14 days . Shouldn't it be 11 years, 3 months and 14 days ?

I have tried quite a few different ways and I always end up with 2 months instead of 3. Does anyone know why?

Try using PHP's built-in date API instead of doing the math yourself.

Using DateTime , DateInterval and the DateTime::diff function:

$date1 = new DateTime("2000-01-01");
$date2 = new DateTime("2011-03-14");
$diff = $date2->diff($date1);
var_dump($diff);'
/* is prints: 
object(DateInterval)#3 (8) {
  ["y"]=>
  int(11)
  ["m"]=>
  int(2)
  ["d"]=>
  int(13)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(4090)
}
*/

At least then you don't need to worry if you made an error (the result seems correct).

你得到的答案是完全正确的!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM