我的客户希望我使用存储在 mysql 中的孩子的出生日期来显示孩子的年龄。我以前的代码不适用于所有格式,因为该站点不限制用户输入此日期的方式。到目前为止,这是我所拥有的,但我无法弄清楚如何检查格式。他们在mm/dd/yyyy
, mm/dd/yy
, dd/mm/yyyy
, dd/mm/yy
, Abbrev day, yy
,过生日Abbrev day, yyyy
。他们还使用不同的分隔符,例如.
或-
很容易检查和使用爆炸。
$birthday=//data from db
$DOB=$birthday;
if(strpos($DOB,'/')){
list($month,$day,$year)=explode('/',$DOB);
if(strlen($year)=='4'){
//year is in Y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
}else{
if(strlen($month)=='4'){
//format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
$age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) > date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
}else{
//year is in y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("y")-$year)-1):(date("y")-$year));
}
}
}elseif(strpos($DOB,'-')){
list($month,$day,$year)=explode('-',$DOB);
if(strlen($year)=='4'){
//year is in Y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
}else{
if(strlen($month)=='4'){
//format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
$age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) > date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
}else{
//year is in y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("y")-$year)-1):(date("y")- $year));
}
}
}elseif(strpos($DOB,'.')){
list($month,$day,$year)=explode('.',$DOB);
if(strlen($year)=='4'){
//year is in Y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
}else{
if(strlen($month)=='4'){
//format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
$age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) > date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
}else{
//year is in y format
$age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) > date("md") ? ((date("y")-$year)-1):(date("y")- $year));
}
}
}else{}
echo $age;
}