」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何用不同的程式方法(PHP 和 MySQL)根據出生日期計算使用者年齡?

如何用不同的程式方法(PHP 和 MySQL)根據出生日期計算使用者年齡?

發佈於2024-11-10
瀏覽:190

How to Calculate User Age from Date of Birth in Different Programming Approaches (PHP and MySQL)?

如何在代碼中根據出生日期計算年齡

根據使用者的出生日期計算年齡是一項常見的程式設計任務。在PHP 中,有許多方法可以實現這一點:

使用物件導向的DateTime 類別(PHP >= 5.3.0)

// Instantiate a DateTime object for the birth date
$birthDate = new DateTime('1999-03-15');

// Instantiate a DateTime object for the current date
$currentDate = new DateTime('now');

// Calculate the difference between the two dates in years
$age = $currentDate->diff($birthDate)->y;

// Output the age
echo $age;

使用過程日期函數 (PHP >= 5.3.0)

// Calculate the difference between the dates using date_diff()
$age = date_diff(date_create('1999-03-15'), date_create('now'))->y;

// Output the age
echo $age;

使用MySQL查詢(MySQL >= 5.0.0)

如果出生日期儲存在MySQL資料庫中,則可以執行下列查詢來計算年齡:

SELECT TIMESTAMPDIFF(YEAR, '1999-03-15', CURDATE()) AS age;

此查詢計算指定日期之間的差異和目前日期(以年為單位)並將其作為年齡列返回。

版本聲明 本文轉載於:1729731918如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3