2009-07-11 14 views
12

Estoy buscando una función que calcula los años a partir de una fecha en formato: 0000-00-00. Encontré esta función, pero no funcionará.Calcular años a partir de la fecha

// 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'); 

salidas nada:/
tengo informar sobre el error, pero no consigo ningún error

+0

Esta función no tiene 'línea de return', por lo que no hace nada de salida. Parece muy incompleto. – deceze

Respuesta

29

Su código no funciona porque la función no devuelve nada para imprimir.

En cuanto a los algoritmos van, ¿qué tal esto:

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 

Este es el mismo algoritmo (justo en PHP) como la respuesta aceptada in this question.

Una forma más corta de hacerlo:

function getAge($then) { 
    $then = date('Ymd', strtotime($then)); 
    $diff = date('Ymd') - $then; 
    return substr($diff, 0, -4); 
} 
+0

dulce! gracias señor –

+0

podría ir más allá y calcular el decimal de años ... – jsnfwlr

+0

En la segunda forma de hacerlo, no debería modificar la entrada $ entonces. Debe almacenar esto como una variable separada. – hawaiianchimp

2

necesita devolver $ yearDiff, creo.

6

Una forma alternativa de hacerlo es con la DateTime class PHP que es nueva a partir de PHP 5.2:

$birthdate = new DateTime("1986-06-18"); 
$today  = new DateTime(); 
$interval = $today->diff($birthdate); 
echo $interval->format('%y years'); 

See it in action

+0

Corrección pequeña: DateTime :: diff() es nuevo a partir de PHP 5.3 – turibe

1

Un único la función de línea puede funcionar aquí

function calculateAge($dob) { 
    return floor((time() - strtotime($dob))/31556926); 
} 

para calcular la edad

$age = calculateAge('1990-07-10'); 
Cuestiones relacionadas