前言
有時(shí)候,我們希望通過身份證來計(jì)算出年齡,那么下面我寫的函數(shù)很適合。
實(shí)現(xiàn)
代碼中已有詳細(xì)注釋。
function getAge($id){ # 1.從身份證中獲取出生日期 $id = $id;//身份證 $birth_Date = strtotime(substr($id, 6, 8));//截取日期并轉(zhuǎn)為時(shí)間戳 # 2.格式化[出生日期] $Year = date('Y', $birth_Date);//yyyy $Month = date('m', $birth_Date);//mm $Day = date('d', $birth_Date);//dd # 3.格式化[當(dāng)前日期] $current_Y = date('Y');//yyyy $current_M = date('m');//mm $current_D = date('d');//dd # 4.計(jì)算年齡() $age = $current_Y - $Year;//今年減去生日年 if($Month > $current_M || $Month == $current_M $Day > $current_D){//深層判斷(日) $age--;//如果出生月大于當(dāng)前月或出生月等于當(dāng)前月但出生日大于當(dāng)前日則減一歲 } # 返回 return $age; }
使用
通過調(diào)用 getAge() 方法,傳入身份證號即可計(jì)算。
# 參數(shù)必須為 String 型 echo getAge('130322xxxxxxxxxx14'); // xx
小編再為大家分享一段代碼:身份證獲取年齡信息:
/* * 根據(jù)身份證號碼獲取年齡 * inupt $code = 完整的身份證號 * return $age : 年齡 */ function ageVerification($code){ $age_time = strtotime(substr($code, 6, 8)); if($age_time === false){ return false; } list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age_time)); $now_time = strtotime("now"); list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now_time)); $age = $y2 - $y1; if((int)($m2.$d2) (int)($m1.$d1)){ $age -= 1; } return $age; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:南陽 宜賓 鎮(zhèn)江 婁底 黃南 湛江 銅川 寶雞
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php實(shí)現(xiàn)根據(jù)身份證獲取精準(zhǔn)年齡》,本文關(guān)鍵詞 php,實(shí)現(xiàn),根據(jù),身份證,獲取,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。