如何使用PHP从出生日期算起年龄?

时间:2018-12-20 17:17:43

标签: php

我的代码:

<?php
  echo date('d/ m /Y', strtotime($reg_bday));
?>

如何使用此功能计算年龄?

2 个答案:

答案 0 :(得分:0)

您可以使用Carbon PHP类https://carbon.nesbot.com/docs/

Carbon::createFromDate(1991, 7, 19)->diff(Carbon::now())->format('%y years, %m months and %d days')

输出类似“ 23年6个月26天”

或基于其他答案https://stackoverflow.com/a/3776843/5441049的本地PHP

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?> 

答案 1 :(得分:0)

简短回答:

function calc_age($date)
{
   return((int)date_diff(date_create($date),date_create('today'))->y);
}

使用:

echo calc_age("1967/03/12");

相关链接: