以 PHP 计算两个日期之间的月数?
如果不使用 PHP 5.3 的 date_diff 函数(我使用的是 PHP 5.2.17),有没有一种简单而准确的方法来做到这一点?我正在考虑类似于下面的代码,但我不知道如何解释闰年:
$days = ceil(abs( strtotime('2000-01-25') - strtotime('2010-02-20') ) / 86400);
$months = ???;
我试图计算出一个人有多少个月大。
如果不使用 PHP 5.3 的 date_diff 函数(我使用的是 PHP 5.2.17),有没有一种简单而准确的方法来做到这一点?我正在考虑类似于下面的代码,但我不知道如何解释闰年:
$days = ceil(abs( strtotime('2000-01-25') - strtotime('2010-02-20') ) / 86400);
$months = ???;
我试图计算出一个人有多少个月大。
$date1 = '2000-01-25';
$date2 = '2010-02-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
您可能还想在某个地方包含这些日子,具体取决于您是否是指整个月。希望你明白这个想法。
这是我的解决方案。它检查日期的年份和月份并找出差异。
$date1 = '2000-01-25';
$date2 = '2010-02-20';
$d1=new DateTime($date2);
$d2=new DateTime($date1);
$Months = $d2->diff($d1);
$howeverManyMonths = (($Months->y) * 12) + ($Months->m);