2009-07-11 2 views
12

Sto cercando una funzione che calcola gli anni da una data nel formato: 0000-00-00. Trovato questa funzione, ma non funzionerà.Calcola anni dalla data

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

uscite niente:/
ho la segnalazione degli errori su, ma io non ottenere gli eventuali errori

+0

Questa funzione non ha alcuna linea 'return', quindi non è così uscita nulla. Sembra molto incompleto. – deceze

risposta

29

Il codice non funziona perché la funzione non restituisce nulla per la stampa.

Per quanto riguarda gli algoritmi di andare, come su questo:

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 

Questo è lo stesso algoritmo (solo in PHP) come la risposta accettata in this question.

Un modo più breve per farlo:

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

dolce! grazie signore –

+0

potresti andare oltre e calcolare il numero decimale degli anni ... – jsnfwlr

+0

Nel secondo modo di farlo, non dovresti modificare l'input $ allora. Si dovrebbe memorizzare questo come una variabile separata. – hawaiianchimp

2

è necessario restituire $ yearDiff, credo.

6

Un modo alternativo per farlo è con di DateTime class PHP che è nuovo a partire da 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

Piccola correzione: DateTime :: diff() è nuovo a partire da PHP 5.3 – turibe

1

Un unico la funzione di linea può funzionare qui

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

Per calcolare l'età

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