douzuizhuo0587 2019-05-16 06:53 采纳率: 0%
浏览 404
已采纳

如何将出生日期转换为年龄(年,月,日)和年龄(年,月,日)到出生日期转换为PHP?

I have a form where the user can input a patient age in years, months and days. That will save the data in the database according to the patient's date of birth. The problem is I'm using strtotime() function to get the DOB of the patient, but when I want to show the age (years, months, days) from retrieving the date form the birthday column, sometimes it showing 1 or 2 days (+-) result. I'm using date_diff() function to retrieving the age (years, months, days). Any solution for my problem ?


$today = date("Y-m-d");
$dateOfBirth = strtotime("$today -2 years -2 months -20 days");
$birthday = date("Y-m-d", $dateOfBirth);

//and then tried to retrieve the age from that date which give me wrong answer

$diff = date_diff(date_create($birthday), date_create($today));

echo $diff->y; // showing 2
echo $diff->m; // showing 2
echo $diff->d; // showing 22 (it should be 20)

  • 写回答

3条回答 默认 最新

  • dongtiao0657 2019-05-16 07:01
    关注

    Update the following line in your code to this:

    $diff = date_diff(date_create($today), date_create($birthday));
    

    Test it here: http://sandbox.onlinephpfunctions.com/code/9dece465739e2315be32b7882ba3ca9a5d9d65b3

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab