开发者

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 answer that you are getting is completely right!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜