프로그래밍/Javascript

[Javascript, 자바스크립트]만 19세 미만 체크하기, 나이 체크 함수

미냐님 2024. 4. 19. 12:13
728x90

function isAdult(year, month, day) {
  const today = new Date();
  const birthday = new Date(year, month - 1, day);
  const diffYear = today.getFullYear() - birthday.getFullYear();
  const diffMonth = today.getMonth() - birthday.getMonth();
  const diffDay = today.getDate() - birthday.getDate();

  // 년도 차이가 19이면 월과 일 차이도 체크
  if (diffYear === 19) {
    // 월 차이가 마이너스면 아직 생일이 지나지 않은 상태
    if (diffMonth < 0) {
      return true; // 만 19세 미만
    } else if (diffMonth === 0) {
      if (diffDay < 0) {
        return true; // 만 19세 미만
      } else {
        return false; // 만 19세 이상
      }
    } else {
      return false; // 만 19세 이상
    }
  } else if (diffYear < 19) {
    return true; // 아직 19세 미만
  } else {
    return false; // 19세 이상
  }
}
728x90