자바스크립트 만나이 계산하기

한국식 나이는 태어나자마자 1살로 간주하고 매년 1월 1일 한 살씩 나이를 더하는 방식이다.

만 나이는 생일을 기준으로 계산한 나이로서 출생한 순간 0세부터 시작하며, 생일이지나면 1세가 증가하는 방식이다.

예를 들어(25년 2월 12일 기준):

  • 2023년 5월 10일 출생 → 2023년 5월 10일에는 0세
  • 2024년 5월 10일(첫 번째 생일)1세
  • 2025년 5월 10일(두 번째 생일)2세

만 나이 계산기

만 나이:
// date 객체를 매개변수로 받는 함수
function calcAgeByDate(birthday) {
  const today = new Date();
  const birthDate = new Date(birthday);

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  const dayDiff = today.getDate() - birthDate.getDate();

  // 생일이 아직 지나지 않았다면 나이를 1 감소
  if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
    age--;
  }

  return age;
}

// 년월일 값을 매개변수로 받는 함수
function calcFullAgeByYearMonthDay(year, month, day) {
  const today = new Date();
  const birthDate = new Date(year, month - 1, day); // month는 0부터 시작하므로 -1 필요

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  const dayDiff = today.getDate() - birthDate.getDate();

  // 생일이 아직 지나지 않았다면 나이를 1 감소
  if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
    age--;
  }

  return age;
}

Leave a Comment