คิดว่าฉันจะทิ้งเรื่องนี้ไว้ที่นี่เพราะนี่เป็นรูปแบบที่ได้รับความนิยมมากที่สุดของคำถามนี้
ฉันวิ่งเปรียบเทียบ 100 ปีในวันที่ 3 ในประเภทที่นิยมมากที่สุดของ funcs อายุฉันสามารถหาสำหรับ PHP และโพสต์ผลของฉัน (เช่นเดียวกับฟังก์ชั่น) เพื่อบล็อกของฉัน
อย่างที่คุณเห็นนั่นทั้ง 3 ฟังก์ชั่น preform นั้นมีความแตกต่างเพียงเล็กน้อยในฟังก์ชั่นที่ 2 ข้อเสนอแนะของฉันตามผลลัพธ์ของฉันคือการใช้ฟังก์ชันที่ 3 ยกเว้นว่าคุณต้องการทำบางสิ่งบางอย่างในวันเกิดของบุคคลซึ่งในกรณีนี้ฟังก์ชันที่ 1 ให้วิธีที่ง่ายในการทำสิ่งนั้น
พบปัญหาเล็ก ๆ ด้วยการทดสอบและปัญหาอื่น ๆ ด้วยวิธีที่ 2! อัปเดตในบล็อกเร็ว ๆ นี้! สำหรับตอนนี้ฉันจะรับทราบวิธีที่สองยังคงเป็นวิธีที่ได้รับความนิยมมากที่สุดที่ฉันพบทางออนไลน์และยังเป็นวิธีที่ฉันค้นหาความไม่ถูกต้องที่สุดด้วย!
คำแนะนำของฉันหลังจากการตรวจสอบ 100 ปี:
หากคุณต้องการสิ่งที่ยืดยาวขึ้นเพื่อให้คุณสามารถรวมถึงโอกาสเช่นวันเกิดและเช่น:
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');
แต่ถ้าคุณเพียงต้องการทราบอายุและไม่มีอะไรเพิ่มเติมแล้ว:
function getAge($date) { // Y-m-d format
return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}
getAge('1980-02-29');
หมายเหตุสำคัญเกี่ยวกับstrtotime
วิธีการ:
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()
เห็นด้วยบางครั้งสำหรับรูปแบบที่เราจำเป็นต้องใช้ ดูเหมือนว่ามันจะคำนวณstrtotime()
ด้วยรูปแบบนั้น