【问题标题】:How to convert Birth date to age ( years, months, days ) and age( years, months, days ) to birth date conversion in PHP?如何在 PHP 中将出生日期转换为年龄(年、月、日)和年龄(年、月、日)转换为出生日期?
【发布时间】:2019-05-16 06:53:13
【问题描述】:

我有一个表格,用户可以在其中输入患者的年龄(年、月和日)。这将根据患者的出生日期将数据保存在数据库中。问题是我正在使用 strtotime() 函数来获取患者的出生日期,但是当我想显示从生日列中检索日期的年龄(年、月、日)时,有时它显示 1 或 2 天 (+-) 结果。我正在使用 date_diff() 函数来检索年龄(年、月、日)。我的问题有什么解决方案吗?


$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)

【问题讨论】:

    标签: php date datetime


    【解决方案1】:

    将代码中的以下行更新为:

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

    在这里测试:http://sandbox.onlinephpfunctions.com/code/9dece465739e2315be32b7882ba3ca9a5d9d65b3

    【讨论】:

      【解决方案2】:

      我希望你做得很好,我阅读了你的问题并根据我的研究和知识找到了以下解决方案。

      希望这能帮助您解决问题。

      =>要根据出生率获取总年份,您可以使用以下代码。

      $bday = new DateTime('10.01.2001'); // Your date of birth
      $today = new Datetime(date('m.d.y'));
      $diff = $today->diff($bday);
      printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d); //You will get your age
      

      您可以将代码复制并粘贴到Fiddle 以测试输出。 使用这个你肯定会得到你的出生日期的年龄。

      提前致谢!

      【讨论】:

        【解决方案3】:

        我写了一个简单的函数Calc_Age() 来计算这个,它非常准确和精确,我希望它是你正在寻找的......在我的代码下面:

        <!DOCTYPE html>
        
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>Patient Age Information</title>
        </head>
        
        <body>
        <?php
          function Calc_Age($myday) {
            date_default_timezone_set('Europe/Rome');
            $birth = new DateTime($myday);
            $birth->format('Y-m-d');
            $today = new DateTime('NOW');
            $today->format('Y-m-d');
            $diffs = $today->diff($birth);
            $myage = $diffs->y . ($diffs->y == 1 ? ' year, ' : ' years, ');
            $myage .= $diffs->m . ($diffs->m == 1 ? ' month and ' : ' months and ');
            $myage .= $diffs->d . ($diffs->d == 1 ? ' day' : ' days');
            return $myage;
          }
        ?>
        
        
        
        <h1>Patient: Angela Bennet</h1>
        
        <p>Angela Bennet is <?php echo Calc_Age("1967-01-23"); ?> old</p>
        
        <h1>Patient: Jhon Malkovich</h1>
        
        <p>Jhon Malkovich is <?php echo Calc_Age("1977-04-14"); ?> old</p>
        
        </body>
        
        </html>
        

        结果:

        我希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2020-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多