可以通过计算当前日期与出生日期之间的差值来算出年龄。具体步骤如下:
-
获取当前日期和出生日期,可以使用PHP内置函数date()和strtotime()来获取。
-
计算出生日期到当前日期的秒数差,可以使用PHP内置函数strtotime()。
-
将秒数差转换成年份差,即得到年龄。可以使用PHP内置函数floor()来向下取整。
举个例子,假设出生日期为1990年1月1日,当前日期为2021年8月1日:
- 获取当前日期和出生日期:
$current_date = date("Y-m-d");
$birthday = "1990-01-01";
- 计算出生日期到当前日期的秒数差:
$diff_seconds = strtotime($current_date) - strtotime($birthday);
- 将秒数差转换成年份差:
$age = floor($diff_seconds / (365 24 60 * 60));
最终得到的$age即为年龄。