日期:2014-05-17  浏览次数:20453 次

PHP 如何计算年龄,域名年龄?已知 YYYY-mm-dd。求域名年龄。
如何计算域名年龄困扰了很久,自己写了一个函数,但是是错误的,因为有的年份是闰年的。


<?php 


//时间输入必须单位
function mathAge($ymd2){
    $ymd1 = "2012-2-27";
    @list($y1,$m1,$d1) = explode("-",date("Y-m-d", strtotime($ymd1)));
    @list($y2,$m2,$d2) = explode("-",date("Y-m-d", strtotime($ymd2)));
    
    $arr = array(
    "年" =>  round( $y1-$y2 ),
    "月" =>  round( $m1-$m2 ),
    "天" =>  round( $d1-$d2 ),
    );

    $arr["天"] = round($d1-$d2);
    while ($arr["天"] < 0) {
        $arr["天"] += 30;
        $arr["月"] -= 1;
    }
    
    while ($arr["月"] < 0) {
     $arr["月"] += 12;
     $arr["年"] -= 1;
    }
    $txt = '';
    foreach ($arr as $k => $v)
    {
        if(!$v)  continue;
        $txt .= $v.$k;
    }
    echo "$ymd1 - $ymd2 = $txt \n";
    return $txt;
  }

  $dateArr = array(
  "2011-12-28",
  "2011-12-29",
  "2011-12-27",
  
  "2010-12-28",
  "2010-12-29",
  "2010-12-27",
  
  "2011-10-1",
  "2010-5-1",
  "2010-2-28",
  
  "1995-1-1",
  "1995-12-31",
  );
  foreach ($dateArr as $date)
  {
      mathAge($date);
      
  }
?>



以上输出测试内容为:


2012-2-27 - 2011-12-28 = 1月29天 
2012-2-27 - 2011-12-29 = 1月28天 
2012-2-27 - 2011-12-27 = 2月 
2012-2-27 - 2010-12-28 = 1年1月29天 
2012-2-27 - 2010-12-29 = 1年1月28天 
2012-2-27 - 2010-12-27 = 1年2月 
2012-2-27 - 2011-10-1 = 4月26天 
2012-2-27 - 2010-5-1 = 1年9月26天 
2012-2-27 - 2010-2-28 = 1年11月29天 
2012-2-27 - 1995-1-1 = 17年1月26天 
2012-2-27 - 1995-12-31 = 16年1月26天 

如何计算好两个日期之间相差的年月?考虑闰年 2月份。
------解决方案--------------------
好吧,我也不是很清楚,不过特意过来顶一下楼主