dongshuobei1037 2018-12-20 17:17
浏览 33

如何使用PHP计算出生日期的年龄? [重复]

This question already has an answer here:

My Code :

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

How to calculate age with this function?

</div>
  • 写回答

2条回答 默认 最新

  • duanjipiao7076 2018-12-20 17:24
    关注

    You can use Carbon PHP class https://carbon.nesbot.com/docs/

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

    Output like "23 years, 6 months and 26 days"

    Or native PHP based on another answer https://stackoverflow.com/a/3776843/5441049

    <?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;
    ?> 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题