복붙노트

PHP는 연령 계산

PHP

PHP는 연령 계산

DOB / mm / yyyy 형식의 DOB가 주어진 사람의 나이를 계산하는 방법을 찾고 있습니다.

어떤 종류의 글리치로 인해 while 루프가 끝나지 않고 전체 사이트를 멈추게 할 때까지 몇 달 동안 잘 작동하는 다음 함수를 사용했습니다. 하루에 여러 번이 기능을 수행하는 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에 대한 1986 년 9 월 9 일

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

해결법

  1. ==============================

    1.이것은 잘 작동합니다.

    이것은 잘 작동합니다.

    <?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;
    ?>
    
  2. ==============================

    2.

    $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 형식과 DateTime 클래스 (DateTime :: diff를 통해)로 오인되지 않도록하여 지금부터 몇 년 사이의 숫자를 얻을 수 있습니다 및 목표 날짜.

  3. ==============================

    3.

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

    4.나는 이것을 위해 날짜 / 시간을 사용한다 :

    나는 이것을 위해 날짜 / 시간을 사용한다 :

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

    5.dob에서 Age를 계산하는 간단한 방법 :

    dob에서 Age를 계산하는 간단한 방법 :

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

    31556926은 1 년의 초 수입니다.

  6. ==============================

    6.나는 이것이 효과가 있으며 단순하다는 것을 알았다.

    나는 이것이 효과가 있으며 단순하다는 것을 알았다.

    strtotime은 1970-01-01에서 시간을 계산하기 때문에 1970에서 뺍니다 (http://php.net/manual/en/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
    
  7. ==============================

    7.// 나이 계산기

    // 나이 계산기

    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);
    
  8. ==============================

    8.dob 사용 연령을 caculate하려면이 기능을 사용할 수도 있습니다. 그것은 DateTime 객체를 사용합니다.

    dob 사용 연령을 caculate하려면이 기능을 사용할 수도 있습니다. 그것은 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;
    
    }
    
  9. ==============================

    9.이것이이 질문의 가장 인기있는 형태 인 것 같기 때문에 나는 이것을 여기에 던질 것이라고 생각했다.

    이것이이 질문의 가장 인기있는 형태 인 것 같기 때문에 나는 이것을 여기에 던질 것이라고 생각했다.

    나는 PHP에서 찾을 수있는 가장 인기있는 세 가지 유형의 3 가지 함수에 대해 100 년 간 비교를 실행하고 내 결과 (기능은 물론)를 블로그에 게시했습니다.

    거기에서 볼 수 있듯이, 세 가지 기능 모두 제 2 기능의 약간의 차이만으로 잘 형성됩니다. 내 결과에 기반한 제 제안은 사람의 생일에 특정한 것을하고 싶지 않으면 3 번째 기능을 사용하는 것입니다.이 경우 첫 번째 기능은 그 일을하는 간단한 방법을 제공합니다.

    내 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.
    
  10. ==============================

    10.DateTime의 API 확장 인 Carbon 라이브러리를 사용할 수 있습니다.

    DateTime의 API 확장 인 Carbon 라이브러리를 사용할 수 있습니다.

    할 수있는 일 :

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

    또는:

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

    11.

      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;
      }
    
  12. ==============================

    12.나는이 스크립트를 신뢰할만한 것으로 발견했다. YYYY-mm-dd로 날짜 형식을 취하지 만 다른 형식으로도 쉽게 수정할 수 있습니다.

    나는이 스크립트를 신뢰할만한 것으로 발견했다. 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;
    }
    
  13. ==============================

    13.

    $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);
    
  14. ==============================

    14.i18n :

    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
    
  15. ==============================

    15.당신이 위대한 정밀도, 그냥 년의 번호를 필요하지 않으면 아래의 코드를 사용하여 고려해 볼 수 있습니다 ...

    당신이 위대한 정밀도, 그냥 년의 번호를 필요하지 않으면 아래의 코드를 사용하여 고려해 볼 수 있습니다 ...

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

    이것을 함수에 넣고 날짜 "1971-11-20"을 변수로 바꾸면됩니다.

    위 코드의 정밀도는 윤년 때문에 높지 않습니다. 즉, 약 4 년마다 365 일 대신 366 일입니다. 60 * 60 * 24 * 365 표현식은 1 년 동안의 초 수를 계산합니다. 31536000으로 교체하십시오.

    또 다른 중요한 점은 유닉스 타임 스탬프를 사용하기 때문에 1901 년과 2038 년의 문제가 있기 때문에 위의 표현이 1901 년 이전과 2038 년 이전의 날짜에는 올바르게 작동하지 않는다는 것을 의미합니다.

    위에서 언급 한 제한 사항을 따라 살 수 있다면 코드가 도움이 될 것입니다.

  16. ==============================

    16.이것은 연, 월, 일별로 나이를 특정으로 반환하여 생체 인식 (DOB)을 계산하는 기능입니다.

    이것은 연, 월, 일별로 나이를 특정으로 반환하여 생체 인식 (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 );
    }
    

    이것을 사용하는 방법

    $age = ageDOB(1984,5,8); /* with my local time is 2014-07-01 */
    echo sprintf("age = %d years %d months %d days",$age['y'],$age['m'],$age['d']); /* output -> age = 29 year 1 month 24 day */
    
  17. ==============================

    17.

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

    18.좀 더 새로운 기능을 사용하는 것처럼 보이지 않는 경우, 여기에 제가 채찍질 한 것입니다. 아마 당신이 필요로하는 것 이상으로 더 좋은 방법이있을 것이라고 확신합니다. 그러나 쉽게 읽을 수 있습니다. 그래서 그 일을해야합니다 :

    좀 더 새로운 기능을 사용하는 것처럼 보이지 않는 경우, 여기에 제가 채찍질 한 것입니다. 아마 당신이 필요로하는 것 이상으로 더 좋은 방법이있을 것이라고 확신합니다. 그러나 쉽게 읽을 수 있습니다. 그래서 그 일을해야합니다 :

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

    희망이 도움이됩니다.

  19. ==============================

    19.윤년으로 인해 하나의 날짜를 다른 날짜에서 뺀 다음이를 몇 년으로 줄이는 것은 현명한 방법이 아닙니다. 인간과 같은 나이를 계산하려면 다음과 같은 것이 필요합니다.

    윤년으로 인해 하나의 날짜를 다른 날짜에서 뺀 다음이를 몇 년으로 줄이는 것은 현명한 방법이 아닙니다. 인간과 같은 나이를 계산하려면 다음과 같은 것이 필요합니다.

    $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--;
    }
    
  20. ==============================

    20.다음 작품은 저에게 잘 맞으며 이미 제시된 예보다 훨씬 더 단순합니다.

    다음 작품은 저에게 잘 맞으며 이미 제시된 예보다 훨씬 더 단순합니다.

    $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;
    }
    

    나는이 코드를 테스트하고 적극적으로 사용했지만 조금 성가신 것처럼 보일 수도 있지만 사용하고 편집하는 것은 매우 간단하며 정확합니다.

  21. ==============================

    21.첫 번째 논리 다음에 =를 사용해야합니다.

    첫 번째 논리 다음에 =를 사용해야합니다.

    <?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.
    
    ?>
    
  22. ==============================

    22.DD / MM / YYYY와 함께 strtotime을 사용할 때 문제가됩니다. 그 형식을 사용할 수 없습니다. 대신에 MM / DD / YYYY (또는 YYYYMMDD 또는 YYYY-MM-DD와 같은 많은 다른 것들)을 사용할 수 있으며 올바르게 작동해야합니다.

    DD / MM / YYYY와 함께 strtotime을 사용할 때 문제가됩니다. 그 형식을 사용할 수 없습니다. 대신에 MM / DD / YYYY (또는 YYYYMMDD 또는 YYYY-MM-DD와 같은 많은 다른 것들)을 사용할 수 있으며 올바르게 작동해야합니다.

  23. ==============================

    23.이 쿼리를 실행하고 MySQL에서 계산하는 방법은 어떻습니까?

    이 쿼리를 실행하고 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 개월 (한 달 전체 계산)

  24. ==============================

    24.나는 이것을 좋아했다.

    나는 이것을 좋아했다.

    $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;
    }
    
  25. ==============================

    25.이 질문에 대한 대답은 OK이지만 사람이 태어난 해를 계산하기 만하면됩니다. 그러나 공유 할 가치가 있다고 생각했습니다.

    이 질문에 대한 대답은 OK이지만 사람이 태어난 해를 계산하기 만하면됩니다. 그러나 공유 할 가치가 있다고 생각했습니다.

    이 작업은 사용자 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;
    
  26. ==============================

    26.나이를 먹으면서 그럴 수있는 방법이 있습니다. 'YYYYMMDD'형식의 날짜를 숫자로 처리하고 빼십시오. 그런 다음 결과를 10000으로 나눈 후 MMDD 부분을 제거합니다. 단순하고 결코 실패하지 않으며 심지어 도약과 현재 서버 시간을 고려합니다.)

    나이를 먹으면서 그럴 수있는 방법이 있습니다. 'YYYYMMDD'형식의 날짜를 숫자로 처리하고 빼십시오. 그런 다음 결과를 10000으로 나눈 후 MMDD 부분을 제거합니다. 단순하고 결코 실패하지 않으며 심지어 도약과 현재 서버 시간을 고려합니다.)

    출생 이후 또는 대부분 출생지에 대한 전체 날짜로 제공되며 현재 지역 시간 (연령 체크가 실제로 이루어지는 곳)과 관련이 있습니다.

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

    그래서 누군가가 18 또는 21 또는 귀하의 시간대에 100 이하 (출생지 표준 시간대가 생기지 않도록 함)를 확인하려면이 방법을 사용하십시오.

  27. ==============================

    27.이 함수는 년 단위로 나이를 반환합니다. 입력 값은 날짜 형식 (YYYY-MM-DD) 생년월일 문자열입니다 (예 : 2000-01-01).

    이 함수는 년 단위로 나이를 반환합니다. 입력 값은 날짜 형식 (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;
    }
    

    건배, Nir

  28. ==============================

    28.DateTime 객체를 사용하여 이들 중 하나를 시도하십시오.

    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

  29. ==============================

    29.이 시도 :

    이 시도 :

    <?php
      $birth_date = strtotime("1988-03-22");
      $now = time();
      $age = $now-$birth_date;
      $a = $age/60/60/24/365.25;
      echo floor($a);
    ?>
    
  30. ==============================

    30.나이를 계산할 때 다음 방법을 사용합니다.

    나이를 계산할 때 다음 방법을 사용합니다.

    $oDateNow = new DateTime();
    $oDateBirth = new DateTime($sDateBirth);
    
    // New interval
    $oDateIntervall = $oDateNow->diff($oDateBirth);
    
    // Output
    echo $oDateIntervall->y;
    
  31. from https://stackoverflow.com/questions/3776682/php-calculate-age by cc-by-sa and MIT license