Рассчитать годы с даты
Я ищу функцию, которая вычисляет годы с даты в формате: 0000-00-00.
Нашел эту функцию, но она не будет работать.
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
ничего не выводит:/
У меня есть отчет об ошибках, но я не получаю никаких ошибок.
Ответы
Ответ 1
Ваш код не работает, потому что функция ничего не возвращает для печати.
Что касается алгоритмов, как насчет этого:
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
Это тот же алгоритм (только в PHP), как принятый ответ в этом вопросе.
Более короткий способ сделать это:
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
Ответ 2
Альтернативный способ сделать это с помощью PHP класса DateTime, который является новым с PHP 5.2:
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
Посмотрите в действии
Ответ 3
Мне нужно вернуть $yearDiff.
Ответ 4
Здесь может работать одна строка.
function calculateAge($dob) {
return floor((time() - strtotime($dob)) / 31556926);
}
Рассчитать возраст
$age = calculateAge('1990-07-10');