请写一个函数,实现以下功能:
根据生日计算年龄
生日“1994/8/8” 结果 “22岁”;
生日“6 october 2011” 结果“5岁”。
有两种方法,第一种详细点:
<?php
header("content-type:text/html;charset=utf-8");
/*
*function:计算两个日期相隔多少年,多少月,多少天
*param string $date1[格式如:2011-11-5]
*param string $date2[格式如:2012-12-01]
*return array array('年','月','日');
*/
function diffDate($date1,$date2){
if(strtotime($date1)>strtotime($date2)){ //strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
$tmp=$date2;
$date2=$date1;
$date1=$tmp;
}
list($Y1,$m1,$d1)=explode('-',$date1); //把数组中的值赋给一些变量:
list($Y2,$m2,$d2)=explode('-',$date2);
$Y=$Y2-$Y1;
$m=$m2-$m1;
$d=$d2-$d1;
if($d<0){
$d+=(int)date('t',strtotime("-1 month $date2"));
$m--;
}
if($m<0){
$m+=12;
$Y--;
}
return array('year'=>$Y,'month'=>$m,'day'=>$d);
}
$arr=(diffDate('2016-08-04','1994-8-8'));
echo "您今年".$arr['year']."岁了";
二.这种相对来说比较简单:
<?php
header("content-type:text/html;charset=utf-8);
function birthday($birthday){
$age = strtotime($birthday); //strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
if($age === false){
return false;
}
list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); //list()把数组中的值赋给一些变量:
$now = strtotime("now");
list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); //explode()将字符串分割数组
$age = $y2 - $y1;
if((int)($m2.$d2) < (int)($m1.$d1))
$age -= 1;
return $age;
}
echo birthday('1997-03-24');