/*
- 파일명: age-calculator.js
- 위치: /js/
- 기능: 만 나이 계산 관련 JavaScript 함수
- 작성일: 2025-03-08
*/
// ===================================
// 초기화 및 이벤트 바인딩
// ===================================
$(document).ready(function() {
// 라디오 버튼 변경 이벤트 처리
$('input[name="baseDate"]').change(function() {
if($(this).val() === 'custom') {
$('#customDateSection').removeClass('d-none');
} else {
$('#customDateSection').addClass('d-none');
}
});
// 월 변경 시 일 업데이트
$('#birthMonth').change(function() {
updateDays('birthDay', $('#birthYear').val(), $(this).val());
});
// 연도 변경 시 일 업데이트
$('#birthYear').change(function() {
updateDays('birthDay', $(this).val(), $('#birthMonth').val());
});
// 특정 날짜 월 변경 시 일 업데이트
$('#customMonth').change(function() {
updateDays('customDay', $('#customYear').val(), $(this).val());
});
// 특정 날짜 연도 변경 시 일 업데이트
$('#customYear').change(function() {
updateDays('customDay', $(this).val(), $('#customMonth').val());
});
// 폼 제출 이벤트 처리
$('#ageCalculatorForm').submit(function(e) {
e.preventDefault();
// 입력값 유효성 검사
if(!validateForm()) {
return false;
}
// 만 나이 계산
calculateAge();
});
});
// ===================================
// 유틸리티 함수
// ===================================
/**
- 월에 따라 일(day) 선택 옵션 업데이트
- 월과 년도에 따라 해당 월의 마지막 일자를 계산하여 선택 옵션 업데이트
-
- @param {string} daySelectId 일 선택 요소의 ID
- @param {string} year 선택된 연도
- @param {string} month 선택된 월
- @return {void}
*/
function updateDays(daySelectId, year, month) {
if(!month) return;
const daySelect = $('#' + daySelectId);
const currentValue = daySelect.val();
// 해당 월의 마지막 일 계산
const lastDay = new Date(year, month, 0).getDate();
// 기존 옵션 제거 후 기본 옵션 추가
daySelect.empty();
daySelect.append('');
// 일 옵션 추가
for(let i = 1; i <= lastDay; i++) {
const selected = (i == currentValue) ? 'selected' : '';
daySelect.append(``);
}
}
/**
- 폼 입력값 유효성 검사
- 필수 입력 필드 확인 및 날짜 값 유효성 검사
-
- @return {boolean} 유효성 검사 통과 여부
*/
function validateForm() {
// 생년월일 필수 입력 확인
const birthYear = $('#birthYear').val();
const birthMonth = $('#birthMonth').val();
const birthDay = $('#birthDay').val();
if(!birthYear || !birthMonth || !birthDay) {
alert('생년월일을 모두 입력해주세요.');
return false;
}
// 특정 날짜 선택 시 유효성 검사
if($('input[name="baseDate"]:checked').val() === 'custom') {
const customYear = $('#customYear').val();
const customMonth = $('#customMonth').val();
const customDay = $('#customDay').val();
if(!customYear || !customMonth || !customDay) {
alert('특정 날짜를 모두 입력해주세요.');
return false;
}
}
return true;
}
/**
- 만 나이 계산 함수
- 생년월일과 기준일로부터 만 나이와 세는 나이 계산
-
- @return {void}
*/
function calculateAge() {
// 생년월일 가져오기
const birthYear = parseInt($('#birthYear').val());
const birthMonth = parseInt($('#birthMonth').val());
const birthDay = parseInt($('#birthDay').val());
// 생년월일 객체 생성
const birthDate = new Date(birthYear, birthMonth - 1, birthDay);
// 기준일 설정
let baseDate;
if($('input[name="baseDate"]:checked').val() === 'today') {
baseDate = new Date(); // 오늘
} else {
const customYear = parseInt($('#customYear').val());
const customMonth = parseInt($('#customMonth').val());
const customDay = parseInt($('#customDay').val());
baseDate = new Date(customYear, customMonth - 1, customDay);
}
// 만 나이 계산
let koreanAge = baseDate.getFullYear() - birthDate.getFullYear();
// 생일이 지나지 않았으면 1살 빼기
if(
baseDate.getMonth() < birthDate.getMonth() ||
(baseDate.getMonth() === birthDate.getMonth() && baseDate.getDate() < birthDate.getDate())
) {
koreanAge--;
}
// 세는 나이 계산 (현재 연도 - 출생 연도 + 1)
const internationalAge = baseDate.getFullYear() - birthDate.getFullYear() + 1;
// 결과 표시
displayResults(birthDate, baseDate, koreanAge, internationalAge);
}
/**
- 계산 결과 표시 함수
- 계산된 나이와 상세 정보를 화면에 표시
-
- @param {Date} birthDate 생년월일
- @param {Date} baseDate 기준일
- @param {number} koreanAge 만 나이
- @param {number} internationalAge 세는 나이
- @return {void}
*/
function displayResults(birthDate, baseDate, koreanAge, internationalAge) {
// 날짜 포맷팅 함수
function formatDate(date) {
return `${date.getFullYear()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`;
}
// 결과 섹션 표시
$('#resultSection').removeClass('d-none');
// 계산된 나이 표시
$('#koreanAge').text(koreanAge + '세');
$('#internationalAge').text(internationalAge + '세');
// 상세 정보 표시
$('#birthDateText').text(formatDate(birthDate));
$('#baseDateText').text(formatDate(baseDate));
// 일 수 차이 계산 (밀리초 -> 일)
const diffTime = Math.abs(baseDate - birthDate);
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
const diffYears = Math.floor(diffDays / 365);
const remainingDays = diffDays % 365;
$('#ageDiffText').text(`태어난 지 ${diffYears}년 ${remainingDays}일이 지났으며, 총 ${diffDays}일이 경과했습니다`);
// 결과 섹션으로 스크롤
$('html, body').animate({
scrollTop: $('#resultSection').offset().top - 20
}, 500);
}