tech/PHP
생년 월일로 나이 계산
lehero
2024. 7. 9. 08:45
아래는 생년월일로 나이를 계산하는 함수입니다.
<?php
function calculateKoreanAge($birthDate) {
// 생년월일을 DateTime 객체로 변환
$birthDateTime = new DateTime($birthDate);
$currentDateTime = new DateTime();
// 연도 차이를 계산
$age = $currentDateTime->format('Y') - $birthDateTime->format('Y');
// 현재 연도에서 생일이 지났는지 확인
if ($currentDateTime->format('m-d') < $birthDateTime->format('m-d')) {
$age--;
}
return $age;
}
// 생년월일을 입력 받기 (예: '1990-05-15')
$birthDate = '1990-05-15';
$age = calculateKoreanAge($birthDate);
echo "만 나이: " . $age;
?>
생년월일을 datetime으로 변환을 해야 합니다.
$birthDateTime = new DateTime($birthDate);
생일이 지났는지 확인
if ($currentDateTime->format('m-d') < $birthDateTime->format('m-d')) {
$age--;
}