PHP คำนวณอายุ


160

ฉันกำลังมองหาวิธีในการคำนวณอายุของบุคคลให้ DOB ของพวกเขาในรูปแบบ dd / mm / yyyy

ฉันใช้ฟังก์ชั่นต่อไปนี้ซึ่งทำงานได้ดีเป็นเวลาหลายเดือนจนกระทั่งความผิดพลาดบางอย่างทำให้ลูปในขณะนั้นไม่สิ้นสุดและบดทั้งไซต์ให้หยุดชะงัก เนื่องจากมี DOB เกือบ 100,000 แห่งที่ใช้งานฟังก์ชั่นนี้หลายครั้งต่อวันจึงยากที่จะระบุสิ่งที่ทำให้เกิดปัญหานี้

ใครบ้างมีวิธีที่เชื่อถือได้มากขึ้นในการคำนวณอายุ?

//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));       
$tdate = time();

$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
    ++$age;
}
return $age;

แก้ไข: ฟังก์ชั่นนี้ดูเหมือนจะทำงานตกลงบางครั้ง แต่กลับ "40" สำหรับ DOB จาก 14/09/1986

return floor((time() - strtotime($birthdayDate))/31556926);

คำตอบ:


193

ใช้งานได้ดี

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>

1
mktime()เห็นด้วยบางครั้งสำหรับรูปแบบที่เราจำเป็นต้องใช้ ดูเหมือนว่ามันจะคำนวณstrtotime()ด้วยรูปแบบนั้น
GusDeCooL

30
PHP strtotimeเข้าใจรูปแบบวันที่อย่างสมบูรณ์แบบคุณไม่ต้องกังวล: 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. php.net/manual/en/function.strtotime.php
s3v3n

ฟังก์ชั่นนี้มีราคาแพงกว่าโซลูชั่นอื่น ๆ มันมาจากการใช้วันที่มากเกินไป ()
Jarzon

วันที่ตามสัดส่วนที่ดี ขอบคุณ
Roque Mejos

172
$tz  = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
     ->diff(new DateTime('now', $tz))
     ->y;

ตั้งแต่ PHP 5.3.0 คุณสามารถใช้สะดวกDateTime::createFromFormatเพื่อให้แน่ใจว่าวันที่ของคุณจะไม่ถูกเข้าใจผิดว่าเป็นm/d/YรูปแบบและDateIntervalคลาส (ผ่านDateTime::diff) เพื่อรับจำนวนปีระหว่างนี้และวันที่เป้าหมาย


1
ดูดี แต่น่าเสียดายที่เซิร์ฟเวอร์ส่วนใหญ่ในประเทศของฉันยังคงใช้ PHP 5.2.x :(
GusDeCooL

3
จำเป็นต้องใช้เขตเวลาหรือไม่?
André Chalella

127
 $date = new DateTime($bithdayDate);
 $now = new DateTime();
 $interval = $now->diff($date);
 return $interval->y;

ฉันลองใช้ DateTime () ก่อนหน้านี้ แต่นี่ทำให้สคริปต์ค้าง ในบันทึกของฉันฉันเห็นคำเตือน PHP: date (): มันไม่ปลอดภัยที่จะพึ่งพาการตั้งค่าเขตเวลาของระบบแม้เมื่อฉันเพิ่ม date_default_timezone_set ('Europe / Brussels');
stef

1
คุณแน่ใจหรือว่าคุณลบ # ออกก่อนบรรทัดนั้น? คุณควรตั้งค่าใน PHP.ini
Wernight

ปกติแล้วจะปลอดภัยที่จะเพิกเฉยต่อคำเตือนนั้น (โดยเฉพาะในกรณีนั้น)
Wernight

96

ฉันใช้วันที่ / เวลาสำหรับสิ่งนี้:

$age = date_diff(date_create($bdate), date_create('now'))->y;

คุณสามารถใช้สิ่งนี้สำหรับรูปแบบวันที่ในสไตล์อังกฤษ: $ age = date_diff (date_create (str_replace ('/', '.', $ bdate)), date_create ('ตอนนี้')) -> y; เนื่องจากstackoverflow.com/questions/4163641/…
Richard

1
ทางออกที่ง่ายที่สุดเพียงหนึ่งบรรทัด ใช้ได้กับ PHP 5.3 ขึ้นไปเท่านั้น
Rhaymand Tatlonghari

60

วิธีง่าย ๆ สำหรับการคำนวณอายุจาก dob:

$_age = floor((time() - strtotime('1986-09-16')) / 31556926);

31556926 คือจำนวนวินาทีในหนึ่งปี


16
การใช้งานฟังก์ชั่นมากเกินไป ...$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
Mavelo

4
ทางออกที่ดีที่สุด ... ซับ 1 เรียบง่ายและหลีกเลี่ยงการใช้: mktime
Timmy

1
@RobertM ในกรณีนี้แย่ขนาดนั้นเหรอ? ฉันไม่คิดว่าฟังก์ชันเหล่านี้ซับซ้อนหรือ "หนัก"
Dewan159

1
@ Dewan159 ดูที่ประวัติการแก้ไข ... ถูกเปลี่ยนให้ตรงกับโซลูชันของฉัน;)
Mavelo

4
กระโดดวินาที?
ksimka

17

// เครื่องคำนวณอายุ

function getAge($dob,$condate){ 
    $birthdate = new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $dob))))));
    $today= new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $condate))))));           
    $age = $birthdate->diff($today)->y;

    return $age;
}

$dob='06/06/1996'; //date of Birth
$condate='07/02/16'; //Certain fix Date of Age 
echo getAge($dob,$condate);

5
ทางออกที่ดีที่สุดทันสมัย ​​2016
AlexioVay

14

ฉันค้นหางานนี้และเรียบง่าย

ลบออกจากปี 1970 เพราะ strtotime คำนวณเวลาตั้งแต่ 1970-01-01 ( http://php.net/manual/th/function.strtotime.php )

function getAge($date) {
    return intval(date('Y', time() - strtotime($date))) - 1970;
}

ผล:

Current Time: 2015-10-22 10:04:23

getAge('2005-10-22') // => 10
getAge('1997-10-22 10:06:52') // one 1s before  => 17
getAge('1997-10-22 10:06:50') // one 1s after => 18
getAge('1985-02-04') // => 30
getAge('1920-02-29') // => 95

เกือบเป็นจริง ... strtotime () คำนวณเวลาตั้งแต่ 1969-12-31 18:00:00
phoenix

8

หากคุณต้องการคำนวณอายุการใช้งานคุณสามารถใช้ฟังก์ชั่นนี้ได้ มันใช้วัตถุ DateTime

function calcutateAge($dob){

        $dob = date("Y-m-d",strtotime($dob));

        $dobObject = new DateTime($dob);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);

        return $diff->y;

}

8

คิดว่าฉันจะทิ้งเรื่องนี้ไว้ที่นี่เพราะนี่เป็นรูปแบบที่ได้รับความนิยมมากที่สุดของคำถามนี้

ฉันวิ่งเปรียบเทียบ 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');

ดู BLOG


หมายเหตุสำคัญเกี่ยวกับ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.

8

คุณสามารถใช้Carbonไลบรารีซึ่งเป็นส่วนขยาย API สำหรับ DateTime

คุณสามารถ:

function calculate_age($date) {
    $date = new \Carbon\Carbon($date);
    return (int) $date->diffInYears();
}

หรือ:

$age = (new \Carbon\Carbon($date))->age;

1
นี่เป็นวิธีที่สะอาดกว่า แต่ต้องใช้ lib ภายนอกซึ่งอาจไม่ดีที่สุดสำหรับทุกโครงการ
stef

1
คาร์บอนเสนอคุณสมบัติวิเศษที่จะทำage diffInYearsดังนั้นคุณสามารถเขียน:(new \Carbon\Carbon($date))->age
k0pernikus

4

หากคุณไม่ต้องการความแม่นยำมากเพียงแค่จำนวนปีคุณสามารถลองใช้รหัสด้านล่าง ...

 print floor((time() - strtotime("1971-11-20")) / (60*60*24*365));

คุณจะต้องใส่สิ่งนี้ลงในฟังก์ชั่นและแทนที่วันที่ "1971-11-20" ด้วยตัวแปร

โปรดทราบว่าความแม่นยำของรหัสข้างต้นไม่สูงเนื่องจากปีอธิกสุรทินคือทุก ๆ 4 ปีมี 366 ตัวแทน 365 นิพจน์ 60 * 60 * 24 * 365 จะคำนวณจำนวนวินาทีในหนึ่งปี - คุณสามารถ แทนที่ด้วย 31536000

อีกสิ่งที่สำคัญคือเนื่องจากการใช้UNIX Timestamp มีปัญหาทั้งปี 1901 และปี 2038 ซึ่งหมายความว่าการแสดงออกข้างต้นจะไม่ทำงานอย่างถูกต้องสำหรับวันที่ก่อนปี 1901 และหลังจากปี 2038

หากคุณสามารถอยู่กับข้อ จำกัด ดังกล่าวข้างต้นรหัสที่ควรจะทำงานให้คุณ


จะเกิดอะไรขึ้นใน 2038 "ทุกระบบ" จะล้มเหลวหากใช้เวลา ()
Miguel

3
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));       
$tdate = time();
return date('Y', $tdate) - date('Y', $dob);

1
ไม่ทำงาน ฟังก์ชั่นของคุณจะบ่งบอกว่าคนที่เกิดในวันที่ 1 กันยายน 2533 มีอายุเท่ากันกับคนที่เกิดในวันที่ 1 ตุลาคม 2533 - มันจะคำนวณ (2010 - 1990) = 20 สำหรับทั้งคู่
PaulJWilliams

คุณต้องการความแม่นยำอายุเท่าไร เดือน? วัน?
Sergey Eremin

3
  function dob ($birthday){
    list($day,$month,$year) = explode("/",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0)
      $year_diff--;
    return $year_diff;
  }

ดูเหมือนว่าตกลงในบางวัน แต่สำหรับคนอื่น ๆ มันกลับไม่มีอะไรเลยสมมุติว่าถ้าไม่พบกัน?
stef

3

ฉันพบว่าสคริปต์นี้น่าเชื่อถือ ใช้รูปแบบวันที่ในรูปแบบ YYYY-mm-dd แต่สามารถแก้ไขรูปแบบอื่นได้อย่างง่ายดาย

/*
* Get age from dob
* @param        dob      string       The dob to validate in mysql format (yyyy-mm-dd)
* @return            integer      The age in years as of the current date
*/
function getAge($dob) {
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ($day_diff < 0 || $month_diff < 0)
        $year_diff--;

    return $year_diff;
}

2
โปรดดูรายละเอียดว่ามันจะมีประโยชน์อย่างไร การวางฟังก์ชั่นไม่ใช่วิธีตอบที่ถูกต้อง
Starx

3
$birthday_timestamp = strtotime('1988-12-10');  

// Calculates age correctly
// Just need birthday in timestamp
$age = date('md', $birthday_timestamp) > date('md') ? date('Y') - date('Y', $birthday_timestamp) - 1 : date('Y') - date('Y', $birthday_timestamp);

3

i18n:

function getAge($birthdate, $pattern = 'eu')
{
    $patterns = array(
        'eu'    => 'd/m/Y',
        'mysql' => 'Y-m-d',
        'us'    => 'm/d/Y',
    );

    $now      = new DateTime();
    $in       = DateTime::createFromFormat($patterns[$pattern], $birthdate);
    $interval = $now->diff($in);
    return $interval->y;
}

// Usage
echo getAge('05/29/1984', 'us');
// return 28

3

ลองใช้สิ่งเหล่านี้โดยใช้วัตถุ DateTime

$hours_in_day   = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;

$birth_date     = new DateTime("1988-07-31T00:00:00");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";
echo $hours     = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins      = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds   = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";

อ้างอิงhttp://www.calculator.net/age-calculator.html


3

เขียนสคริปต์ PHP เพื่อคำนวณอายุปัจจุบันของบุคคล

วันเดือนปีเกิดตัวอย่าง: 11.4.1987

ตัวอย่างโซลูชั่น:

รหัส PHP:

<?php
$bday = new DateTime('11.4.1987'); // Your date of birth
$today = new Datetime(date('m.d.y'));
$diff = $today->diff($bday);
printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
printf("\n");
?>

ตัวอย่างผลลัพธ์:

อายุของคุณ: 30 ปี 3 เดือน 0 วัน


2

นี่คือฟังก์ชั่นของฉันในการคำนวณ DOB พร้อมผลตอบแทนอายุเฉพาะเจาะจงตามปีเดือนและวัน

function ageDOB($y=2014,$m=12,$d=31){ /* $y = year, $m = month, $d = day */
date_default_timezone_set("Asia/Jakarta"); /* can change with others time zone */

$ageY = date("Y")-intval($y);
$ageM = date("n")-intval($m);
$ageD = date("j")-intval($d);

if ($ageD < 0){
    $ageD = $ageD += date("t");
    $ageM--;
    }
if ($ageM < 0){
    $ageM+=12;
    $ageY--;
    }
if ($ageY < 0){ $ageD = $ageM = $ageY = -1; }
return array( 'y'=>$ageY, 'm'=>$ageM, 'd'=>$ageD );
}

วิธีการใช้งาน

$ อายุ = ageDOB (1984,5,8); / * ตามเวลาท้องถิ่นของฉันคือ 2014-07-01 * /
echo sprintf ("อายุ =% d ปี% d เดือน% d วัน", $ Age ['y'], $ age ['m'], $ age ['d']); / * output -> อายุ = 29 ปี 1 เดือน 24 วัน * /

2

ฟังก์ชันนี้จะคืนค่าอายุในปีที่ผ่านมา ค่าที่ป้อนเป็นวันที่มีการจัดรูปแบบ (YYYY-MM-DD) วันที่เกิดสตริงเช่น: 2000-01-01

มันทำงานได้อย่างแม่นยำ

function getAge($dob) {
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    // if we are any month before the birthdate: year - 1 
    // OR if we are in the month of birth but on a day 
    // before the actual birth day: year - 1
    if ( ($month_diff < 0 ) || ($month_diff === 0 && $day_diff < 0))
        $year_diff--;   

    return $year_diff;
}

ไชโยนิร่า


1

หากคุณไม่สามารถใช้ฟังก์ชั่นใหม่บางอย่างนี่คือสิ่งที่ฉันทำขึ้นมา อาจเป็นมากกว่าที่คุณต้องการและฉันแน่ใจว่ามีวิธีที่ดีกว่า แต่มันอ่านง่ายดังนั้นจึงควรทำงาน:

function get_age($date, $units='years')
{
    $modifier = date('n') - date('n', strtotime($date)) ? 1 : (date('j') - date('j', strtotime($date)) ? 1 : 0);
    $seconds = (time()-strtotime($date));
    $years = (date('Y')-date('Y', strtotime($date))-$modifier);
    switch($units)
    {
        case 'seconds':
            return $seconds;
        case 'minutes':
            return round($seconds/60);
        case 'hours':
            return round($seconds/60/60);
        case 'days':
            return round($seconds/60/60/24);
        case 'months':
            return ($years*12+date('n'));
        case 'decades':
            return ($years/10);
        case 'centuries':
            return ($years/100);
        case 'years':
        default:
            return $years;
    }
}

ตัวอย่างการใช้:

echo 'I am '.get_age('September 19th, 1984', 'days').' days old';

หวังว่านี่จะช่วยได้


1

เนื่องจากปีอธิกสุรทินก็ไม่ควรที่จะลบหนึ่งวันจากอีกวันและเพิ่มจำนวนปี ในการคำนวณอายุอย่างมนุษย์คุณจะต้องมีสิ่งนี้:

$birthday_date = '1977-04-01';
$age = date('Y') - substr($birthday_date, 0, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($birthday_date, 4, 6)) < 0)
{
    $age--;
}

1

ต่อไปนี้ใช้งานได้ดีสำหรับฉันและดูเหมือนจะง่ายกว่าตัวอย่างที่ได้รับ

$dob_date = "01";
$dob_month = "01";
$dob_year = "1970";
$year = gmdate("Y");
$month = gmdate("m");
$day = gmdate("d");
$age = $year-$dob_year; // $age calculates the user's age determined by only the year
if($month < $dob_month) { // this checks if the current month is before the user's month of birth
  $age = $age-1;
} else if($month == $dob_month && $day >= $dob_date) { // this checks if the current month is the same as the user's month of birth and then checks if it is the user's birthday or if it is after it
  $age = $age;
} else if($month == $dob_month && $day < $dob_date) { //this checks if the current month is the user's month of birth and checks if it before the user's birthday
  $age = $age-1;
} else {
  $age = $age;
}

ฉันได้ทดสอบและใช้รหัสนี้อย่างแข็งขันมันอาจดูยุ่งยากเล็กน้อย แต่มันใช้งานและแก้ไขได้ง่ายและค่อนข้างแม่นยำ


1

ตามตรรกะแรกคุณต้องใช้ = ในการเปรียบเทียบ

<?php 
    function age($birthdate) {
        $birthdate = strtotime($birthdate);
        $now = time();
        $age = 0;
        while ($now >= ($birthdate = strtotime("+1 YEAR", $birthdate))) {
            $age++;
        }
        return $age;
    }

    // Usage:

    echo age(implode("-",array_reverse(explode("/",'14/09/1986')))); // format yyyy-mm-dd is safe!
    echo age("-10 YEARS") // without = in the comparison, will returns 9.

?>

downvoted ในขณะที่ทำงานมันไม่มีประสิทธิภาพในการใช้การวนซ้ำเพื่อทำคณิตศาสตร์พื้นฐาน
Wranorn

1

มันเป็นปัญหาเมื่อคุณใช้ strtotime กับ DD / MM / YYYY คุณไม่สามารถใช้รูปแบบนั้นได้ แทนที่จะเป็นคุณสามารถใช้ MM / DD / YYYY (หรืออื่น ๆ อีกมากมายเช่น YYYYMMDD หรือ YYYY-MM-DD) และควรทำงานอย่างถูกต้อง


1

วิธีการเกี่ยวกับการเปิดใช้แบบสอบถามนี้และมี MySQL คำนวณให้คุณ:

SELECT 
username
,date_of_birth
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) DIV 12 AS years
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) MOD 12 AS months
FROM users

ผลลัพธ์:

r2d2, 1986-12-23 00:00:00, 27 , 6 

ผู้ใช้มีอายุ 27 ปี 6 เดือน (นับรวมทั้งเดือน)


นี่เป็นวิธีแก้ปัญหาที่ดีสำหรับผู้ใช้งาน PHP รุ่นก่อน 5.3 ซึ่งไม่มีสิทธิ์เข้าถึง date_diff และอื่น ๆ
strangerstudios

1

ฉันทำอย่างนี้

$geboortedatum = 1980-01-30 00:00:00;
echo leeftijd($geboortedatum) 

function leeftijd($geboortedatum) {
    $leeftijd = date('Y')-date('Y', strtotime($geboortedatum));
    if (date('m')<date('m', strtotime($geboortedatum)))
        $leeftijd = $leeftijd-1;
    elseif (date('m')==date('m', strtotime($geboortedatum)))
       if (date('d')<date('d', strtotime($geboortedatum)))
           $leeftijd = $leeftijd-1;
    return $leeftijd;
}

1

คำตอบที่ดีที่สุดสำหรับเรื่องนี้ก็โอเค แต่มีเพียงปีที่มีคนเกิดมาฉันแค่บิดมันเพื่อจุดประสงค์ในการออกกำลังกายทั้งวันและเดือน แต่คิดว่ามันคุ้มค่าที่จะแบ่งปัน

สิ่งนี้ทำงานได้โดยการประทับเวลาของ DOB ของผู้ใช้ แต่สามารถเปลี่ยนแปลงได้

$birthDate = date('d-m-Y',$usersDOBtimestamp);
$currentDate = date('d-m-Y', time());
//explode the date to get month, day and year
$birthDate = explode("-", $birthDate);
$currentDate = explode("-", $currentDate);
$birthDate[0] = ltrim($birthDate[0],'0');
$currentDate[0] = ltrim($currentDate[0],'0');
//that gets a rough age
$age = $currentDate[2] - $birthDate[2];
//check if month has passed
if($birthDate[1] > $currentDate[1]){
      //user birthday has not passed
      $age = $age - 1;
} else if($birthDate[1] == $currentDate[1]){ 
      //check if birthday is in current month
      if($birthDate[0] > $currentDate[0]){
            $age - 1;
      }


}
   echo $age;

1

หากคุณต้องการได้รับเต็มที่อย่างเต็มที่ตามอายุมีวิธีที่เหนือกว่าในการทำเช่นนั้น รักษาวันที่จัดรูปแบบเป็น 'YYYYMMDD' เป็นตัวเลขและแทนที่พวกเขา หลังจากนั้นยกเลิกส่วน MMDD โดยการหารผลลัพธ์ด้วย 10000 แล้วปูพื้น เรียบง่ายและไม่เคยล้มเหลวแม้ใช้เวลากับบัญชี leapyears และเวลาเซิร์ฟเวอร์ปัจจุบันของคุณ;)

ตั้งแต่วันเกิดหรือส่วนใหญ่จัดให้ตามวันที่เต็มรูปแบบในสถานที่เกิดและพวกเขามีความเกี่ยวข้องกับเวลาท้องถิ่นปัจจุบัน (ที่ตรวจสอบอายุจะทำจริง)

$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birtday)/10000);

ดังนั้นถ้าคุณต้องการตรวจสอบว่ามีใครอายุ 18 หรือ 21 หรือต่ำกว่า 100 ในเขตเวลาของคุณ (ไม่เป็นไรเขตเวลากำเนิด) ตามวันเกิดนี่เป็นวิธีของฉันในการทำสิ่งนี้


โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.