$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));
我得到的答案是
11 years , 2 months and 14 days
.不应该是11 years, 3 months and 14 days
?我尝试了很多不同的方法,但我总是以 2 个月而不是 3 个月结束。有谁知道为什么?
最佳答案
尝试使用 PHP 的内置日期 API 而不是自己进行数学计算。
使用 DateTime , DateInterval和 DateTime::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)
}
*/
至少这样你就不用担心你犯了错误(结果似乎是正确的)。
关于php - 计算日期之间的年/月/日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5309062/