简体   繁体   English

PHP 5.2.6 中的年龄计算

[英]Age Calculation in PHP 5.2.6

I am facing a problem while calculating age saved in the database.我在计算保存在数据库中的年龄时遇到问题。 I obtained help from a user of this site and he gave me the proper output file but i ran into anoth issue.我从该站点的用户那里获得了帮助,他给了我正确的输出文件,但我遇到了另一个问题。 The solution is made for newer php version but the php version i have is 5.2.6.该解决方案适用于较新的 php 版本,但我的 php 版本是 5.2.6。 Any help in this method will be highly appreciated.将不胜感激此方法中的任何帮助。 Here is the code he provided me这是他提供给我的代码

if(!empty($row11['dob'])){ 
            $birthdate = new DateTime($row11['dob']);
            $today     = new DateTime('today');
            $ag = $birthdate->diff($today)->y;
            $mn = $birthdate->diff($today)->m;
            $dy = $birthdate->diff($today)->d;              
        }else{
            $ag = 0; $mn=0; $dy=0;
        }   

I am also attaching the original file so that you can help me better.我还附上了原始文件,以便您可以更好地帮助我。 Please do note that i am using php 5.2.6 for this purpose.请注意,我为此使用了 php 5.2.6。 Any prompt help in this regard will be highly appreciated.在这方面的任何及时帮助将不胜感激。 Thanks谢谢

Here is the link to Original File这是原始文件的链接

Maybe I can help.也许我可以帮忙。 Datetime->diff was introduced in PHP 5.3, so you'd need a workaround. Datetime->diff 是在 PHP 5.3 中引入的,因此您需要一个解决方法。

Not the neatest, but definitely a quick way of doing it is to substract the current date with the birthdate divided by the number of years that passed.不是最简单的,但绝对是一种快速的方法是用生日除以过去的年数减去当前日期。 This would look something like:这看起来像:

$birthdate = new DateTime($row11['dob']);
$today = new DateTime('today');
$year = round(($today->format('U') - $birthdate->format('U')) / (60*60*24*365));

For months, the situation becomes more complicated, but based on the example it doesn't seem like you need much more detail than this.几个月来,情况变得更加复杂,但根据示例,您似乎不需要比这更多的细节。 If you want to account for leapyears I'd suggest extending the formula.如果您想考虑闰年,我建议扩展该公式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM