Bu sorunun en popüler şekli gibi göründüğü için bunu buraya atacağımı düşündüm.
Ben PHP için bulabildiğim en popüler yaş funcs 3 tür 100 yıl karşılaştırma koştu ve benim sonuçları (yanı sıra fonksiyonları) bloguma gönderdi .
Gördüğünüz gibi orada her 3 Funcs 2 fonksiyonu üzerine sadece hafif bir fark ile iyi preform. Sonuçlarıma dayalı önerim, bir kişinin doğum gününde özel bir şey yapmak istemiyorsanız 3. işlevi kullanmaktır, bu durumda 1. işlev tam olarak bunu yapmak için basit bir yol sağlar.
Test ile küçük bir sorun ve 2. yöntemle başka bir sorun bulundu! Güncelleme yakında blogda! Şimdilik, ikinci yöntem hala çevrimiçi bulduğum en popüler yöntemdir ve yine de en yanlışları bulduğum yöntemdir!
100 yıllık incelememden sonra önerilerim:
Daha uzun bir şey istiyorsanız, böylece doğum günleri ve benzeri günleri dahil edebilirsiniz:
function getAge($date) { // Y-m-d format
$now = explode("-", date('Y-m-d'));
$dob = explode("-", $date);
$dif = $now[0] - $dob[0];
if ($dob[1] > $now[1]) { // birthday month has not hit this year
$dif -= 1;
}
elseif ($dob[1] == $now[1]) { // birthday month is this month, check day
if ($dob[2] > $now[2]) {
$dif -= 1;
}
elseif ($dob[2] == $now[2]) { // Happy Birthday!
$dif = $dif." Happy Birthday!";
};
};
return $dif;
}
getAge('1980-02-29');
Ancak sadece yaşı bilmek ve daha fazlasını yapmak istemiyorsanız, o zaman:
function getAge($date) { // Y-m-d format
return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}
getAge('1980-02-29');
strtotimeYöntem hakkında önemli bir not :
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the
separator between the various components: if the separator is a slash (/),
then the American m/d/y is assumed; whereas if the separator is a dash (-)
or a dot (.), then the European d-m-y format is assumed. If, however, the
year is given in a two digit format and the separator is a dash (-, the date
string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or
DateTime::createFromFormat() when possible.
mktime(). phpstrtotime()bu format ile yanlış hesaplanmış gibi görünüyor .