计算日期之间的年/月/日

and*_*ndy 2 php date

$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));
Run Code Online (Sandbox Code Playgroud)

我得到的答案是11 years , 2 months and 14 days.不应该11 years, 3 months and 14 days吗?

我尝试了很多不同的方法,我总是以2个月而不是3个月结束.有谁知道为什么?

edo*_*ian 8

尝试使用PHP的内置日期API,而不是自己做数学.

使用DateTime,DateIntervalDateTime :: diff函数:

$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)
}
*/
Run Code Online (Sandbox Code Playgroud)

至少那你不用担心你是否犯了错误(结果似乎是正确的).