PHP按照生日日期计算当前的实际年龄
2015-11-09 16:58
676 查看
要计算最真实的周岁年龄,精确到生日当天,我的思路是根据生日当天一直到今天的天数,然后去除每年的365天,向下取整获得完整的年数,这个值就是周岁。中间的闰年会让总天数多出来几天,这些多出来的天数剔除出去就行了。
代码如下:
1991-11-09得到的是24,1991-11-10得到的是23,精确到生日当天。
代码如下:
class ComputeYear{ private static $leapYears = 0; public static function getYear($birthday){ $currentDay = new \DateTime(); self::getLeapYears($currentDay->format('Y-m-d'),$birthday); $daysDiff = date_diff($currentDay,date_create($birthday)); $realDays = $daysDiff->days-self::$leapYears; if($realDays >= 365){ $age = floor($realDays / 365); echo 'U r '.$age.' year old!'; }else{ echo "It's a Baby girl"; } } private static function getLeapYears($currentDay,$birthDay){ $currentYear = date('Y',strtotime($currentDay)); $currentMonth = date('m',strtotime($currentDay)); $birthYear = date('Y',strtotime($birthDay)); $birthMonth = date('m',strtotime($birthDay)); if($birthMonth > 2){ $birthYear += 1; } if($currentMonth < 2){ $currentYear += 1; } for($i = $birthYear;$i<=$currentYear;$i++){ if(self::checkLeap($i)){ self::$leapYears++; } } } private static function checkLeap($year){ $time = mktime(20,20,20,2,1,$year); if (date("t",$time)==29){ return true; }else{ return false; } } } ComputeYear::getYear('1991-11-10');
1991-11-09得到的是24,1991-11-10得到的是23,精确到生日当天。
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- oracle sql日期比较
- Php Installing An Expansion
- DB2 日期和时间的函数应用说明
- Delphi实现读取系统时间与日期完整实例
- Country使 MS-DOS 子系统能使用国际时间、日期、货币、大小写转换和小数分隔符
- vbs下通过日期查找文件夹的代码
- PHP+Apache在Windows 9x下的安装和配置
- 用批处理实现的创建带日期的文件夹的代码
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站