我的客戶希望我使用存儲在mysql中的出生日期顯示孩子的年齡。由於該網站未限制用戶輸入此日期的方式,因此我以前的代碼不適用於所有格式。以下是我目前爲止的內容,但我無法確定如何檢查格式。他們有mm/dd/yyyy
,mm/dd/yy
,dd/mm/yyyy
,dd/mm/yy
,Abbrev day, yy
,Abbrev day, yyyy
的生日。他們還使用不同的分隔符,如.
或-
,這很容易檢查並使用爆炸。從任何格式存儲的出生日期查找年齡php
$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;
}
你如何處理03/03/1995?你是否保存每個日期的格式? – 2013-03-12 20:26:38
爲什麼strtotime()不起作用? – 2013-03-12 20:27:32
@Akam,03/03/1995是3月3日。 :)但是你一般都是對的,只是使用了不好的例子。那麼,user2162686,如果你有03/04/1995存儲?它是4月還是4月,3日?只有兩種方法可以處理它:(1)在數據庫中允許的格式(但不一定在UI中)只允許一個格式或(2)與日期並排存儲格式。對你的特殊情況更好 - 這取決於你自己決定。 – J0HN 2013-03-12 20:39:32