從出生日期提取年齡
在包含出生日期的用戶個人資料的資料庫中,計算年齡至關重要。若要將出生日期轉換為年齡,請依照下列步驟操作:
使用PHP (>= 5.3.0)
物件-定向方法:
<code class="php">$from = new DateTime('1970-02-01'); $to = new DateTime('today'); echo $from->diff($to)->y;</code>
過程方法:
<code class="php">echo date_diff(date_create('1970-02-01'), date_create('today'))->y;</code>
使用Myal>使用My0.0.0.0.
<code class="sql">SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age</code>
檢索年齡的範例PHP 代碼
給定以下PHP 程式碼來從資料庫擷取使用者的出生日期:<code class="php">if(isset($_GET['id'])) { $id = intval($_GET['id']); $dnn = mysql_fetch_array($dn); $dn = mysql_query('select username, email, skype, avatar, ' . 'date, signup_date, gender from users where id="'.$id.'"'); $dnn = mysql_fetch_array($dn); echo "{$dnn['date']}"; }</code>
<code class="php">// Additional lines to calculate age $birthDate = new DateTime($dnn['date']); $today = new DateTime('today'); $age = $birthDate->diff($today)->y; echo "{$age}";</code>
<code class="php">// Additional lines to calculate age $birthDate = date_create($dnn['date']); $today = date_create('today'); $age = date_diff($birthDate, $today)->y; echo "{$age}";</code>
以上是如何根據給定的出生日期計算年齡?的詳細內容。更多資訊請關注PHP中文網其他相關文章!