你遇到的最精确的从用户出生日期计算年龄的函数是什么?我有以下代码,想知道如何改进它,因为它不支持所有日期格式,而且也不确定它是否是最准确的函数(符合DateTime标准会更好)。
function getAge($birthday) {
return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
你遇到的最精确的从用户出生日期计算年龄的函数是什么?我有以下代码,想知道如何改进它,因为它不支持所有日期格式,而且也不确定它是否是最准确的函数(符合DateTime标准会更好)。
function getAge($birthday) {
return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
echo $interval->y;
应该可以工作
$date
的格式。http://php.net/datetime.createfromformat -- 我刚测试过了:完美运行。 - KingCrunch请检查这个
<?php
$c= date('Y');
$y= date('Y',strtotime('1988-12-29'));
echo $c-$y;
?>
DateTime
的作用。 - mbomb007 <?php
//full age calulator
$bday = new DateTime('02.08.1991');//dd.mm.yyyy
$today = new DateTime('00:00:00'); // Current date
$diff = $today->diff($bday);
printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
?>
什么鬼?
strtotime(date('d-m-Y'))
你是从当前时间戳生成一个日期字符串,然后再将日期字符串转换回时间戳吗?
顺便说一下,它无法正常工作的原因之一是 strtotime() 假定数字日期是 m/d/y 格式(即日期在前的美国日期格式)。另一个原因是该参数($birthday)在公式中未被使用。
将$date
更改为$birthday
。
这个函数运行良好。
function age($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 && $month_diff==0){$year_diff--;}
if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
return $year_diff;
}
这个有效:
<?
$date = date_create('1984-10-26');
$interval = $date->diff(new DateTime);
echo $interval->y;
?>
如果您告诉我您的$birthday
变量以什么格式出现,我将为您提供准确的解决方案
这是我的长/详细版本(如果您愿意,可以缩短它):
$timestamp_birthdate = mktime(9, 0, 0, $birthdate_month, $birthdate_day, $birthdate_year);
$timestamp_now = time();
$difference_seconds = $timestamp_now-$timestamp_birthdate;
$difference_minutes = $difference_seconds/60;
$difference_hours = $difference_minutes/60;
$difference_days = $difference_hours/24;
$difference_years = $difference_days/365;
为了获得超高的精度,您需要考虑闰年因素:
function get_age($dob_day,$dob_month,$dob_year){
$year = gmdate('Y');
$month = gmdate('m');
$day = gmdate('d');
//seconds in a day = 86400
$days_in_between = (mktime(0,0,0,$month,$day,$year) - mktime(0,0,0,$dob_month,$dob_day,$dob_year))/86400;
$age_float = $days_in_between / 365.242199; // Account for leap year
$age = (int)($age_float); // Remove decimal places without rounding up once number is + .5
return $age;
}
所以使用:
echo get_date(31,01,1985);
或者其他什么...
注意:要查看您的精确年龄到小数点
return $age_float
取而代之。
$birthday
。 - Hardik Patel