PHP는 나이를 계산
DOB를 dd / mm / yyyy 형식으로 지정하여 사람의 나이를 계산하는 방법을 찾고 있습니다.
나는 어떤 종류의 결함으로 인해 while 루프가 끝나지 않고 전체 사이트가 정지 될 때까지 몇 달 동안 잘 작동하는 다음 기능을 사용하고있었습니다. 하루에 여러 번이 기능을 수행하는 거의 10 만 개의 DOB가 있기 때문에이 원인을 파악하기가 어렵습니다.
누구나 나이를 계산하는 데 더 신뢰할만한 방법이 있습니까?
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();
$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
++$age;
}
return $age;
편집 :이 기능은 때때로 제대로 작동하는 것처럼 보이지만 1986 년 9 월 14 일 DOB에 대해 "40"을 반환합니다.
return floor((time() - strtotime($birthdayDate))/31556926);
이것은 잘 작동합니다.
<?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;
?>
$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
현재 날짜와 대상 날짜 사이의 연도 수) 얻을 수 있습니다.
$date = new DateTime($bithdayDate);
$now = new DateTime();
$interval = $now->diff($date);
return $interval->y;
나는 이것을 위해 날짜 / 시간을 사용한다 :
$age = date_diff(date_create($bdate), date_create('now'))->y;
dob에서 나이를 계산하는 간단한 방법 :
$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
31556926
1 년의 초 수입니다.
// 나이 계산기
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);
나는 이것이 효과가 있고 간단하다는 것을 알았다.
strtotime이 1970-01-01 ( http://php.net/manual/en/function.strtotime.php ) 에서 시간을 계산하므로 1970에서 빼기
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
dob 사용 연령을 계산하려면이 기능을 사용할 수도 있습니다. 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;
}
DateTime의 API 확장 인 Carbon
라이브러리 를 사용할 수 있습니다 .
당신은 할 수 있습니다 :
function calculate_age($date) {
$date = new \Carbon\Carbon($date);
return (int) $date->diffInYears();
}
또는:
$age = (new \Carbon\Carbon($date))->age;
이것이이 질문의 가장 인기있는 형태 인 것 같아서 여기에 던질 것이라고 생각했습니다.
나는 PHP에서 찾을 수있는 가장 인기있는 연령 유형의 3 가지에 대해 100 년 비교를 실행하고 내 결과 (함수뿐만 아니라)를 내 블로그에 게시했습니다 .
보시다시피 , 두 번째 기능에 약간의 차이 만 있으면 3 가지 기능이 모두 프리폼됩니다. 내 결과에 근거한 나의 제안은 당신이 사람의 생일에 특정한 것을하고 싶지 않다면 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.
몇 년 만에 큰 정밀도가 필요하지 않으면 아래 코드를 사용하는 것이 좋습니다 ...
print floor((time() - strtotime("1971-11-20")) / (60*60*24*365));
이것을 함수에 넣고 날짜 "1971-11-20"을 변수로 바꾸면됩니다.
위 코드의 정밀도는 윤년으로 인해 높지 않습니다. 즉 약 4 년마다 365 일 대신 366 일입니다. 60 * 60 * 24 * 365 식은 1 년의 초 수를 계산합니다. 31536000으로 교체하십시오.
또 다른 중요한 점은 UNIX 타임 스탬프를 사용하기 때문에 1901 년과 2038 년 문제를 모두 가지고 있다는 것입니다. 이는 위의 표현이 1901 년 이전과 2038 년 이후의 날짜에 대해 올바르게 작동하지 않음을 의미합니다.
위에서 언급 한 제한 사항에 따라 살 수 있다면 해당 코드가 효과적입니다.
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;
}
이 스크립트가 신뢰할 만하다는 것을 알았습니다. 날짜 형식은 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;
}
$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);
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
이것은 연도 별, 월별, 일별 나이로 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']); / * 출력-> 연령 = 29 년 1 개월 24 일 * /
이 함수는 나이를 년 단위로 반환합니다. 입력 값은 날짜 형식 (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;
}
건배
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
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();
return date('Y', $tdate) - date('Y', $dob);
새로운 기능 중 일부를 사용할 수없는 경우 여기에 채찍질이 있습니다. 아마도 당신이 필요로하는 것보다 많을 것입니다. 더 나은 방법이 있지만 확실하게 읽을 수 있으므로 작업을 수행해야합니다.
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';
도움이 되었기를 바랍니다.
윤년으로 인해 한 날짜를 다른 날짜에서 빼고 몇 년으로 나누는 것이 현명한 것은 아닙니다. 인간과 같은 나이를 계산하려면 다음과 같은 것이 필요합니다.
$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--;
}
다음은 저에게 효과적이며 이미 제공된 예보다 훨씬 간단한 것 같습니다.
$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;
}
이 코드를 테스트하고 적극적으로 사용했는데 약간 번거로울 수 있지만 사용 및 편집이 매우 간단하고 정확합니다.
첫 번째 논리에 따라 비교에서 =를 사용해야합니다.
<?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.
?>
It is a problem when you use strtotime with DD/MM/YYYY. You cant use that format. Instead of it you can use MM/DD/YYYY (or many others like YYYYMMDD or YYYY-MM-DD) and it should work properly.
How about launching this query and having MySQL calculating it for you:
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
Result:
r2d2, 1986-12-23 00:00:00, 27 , 6
The user has 27 years and 6 months (it counts an entire month)
I did it like this.
$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;
}
The top answer for this is OK but only calualtes the year a person was born, I tweaked it for my own purposes to work out the day and month. But thought it was worth sharing.
This works by taken a timestamp of the the users DOB, but feel free to change that
$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;
If you want to only get fullyears as age, there is a supersimple way on doing that. treat dates formatted as 'YYYYMMDD' as numbers and substract them. After that cancel out the MMDD part by dividing the result with 10000 and floor it down. Simple and never fails, even takes to account leapyears and your current server time ;)
Since birthays or mostly provided by full dates on birth location and they are relevant to CURRENT LOCAL TIME (where the age check is actually done).
$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birtday)/10000);
so if you want to check if someone is 18 or 21 or below 100 on your timezone (nevermind the origin timezone) by birthday, this is my way to do this
Try this :
<?php
$birth_date = strtotime("1988-03-22");
$now = time();
$age = $now-$birth_date;
$a = $age/60/60/24/365.25;
echo floor($a);
?>
I use the following method to calculate age:
$oDateNow = new DateTime();
$oDateBirth = new DateTime($sDateBirth);
// New interval
$oDateIntervall = $oDateNow->diff($oDateBirth);
// Output
echo $oDateIntervall->y;
참고URL : https://stackoverflow.com/questions/3776682/php-calculate-age
'Programming' 카테고리의 다른 글
JavaScript에서 여러 CSS 스타일을 설정하려면 어떻게해야합니까? (0) | 2020.06.08 |
---|---|
자동 레이아웃을 사용하여 텍스트로 확장되는 UITextView (0) | 2020.06.08 |
모든 줄의 끝에 텍스트를 붙여 넣는 방법? (0) | 2020.06.08 |
표준 컨테이너의 복잡성 보장은 무엇입니까? (0) | 2020.06.08 |
iOS 앱 오류-자체를 하위보기로 추가 할 수 없습니다 (0) | 2020.06.08 |