괴발개발/Spring Framework

나이 계산(생년월일, 년도, 만 나이)

moonday 2021. 9. 8. 12:50

VO파일에 있는 메소드 (student_birthdate변수는 2021-09-08 과 같은 정보를 가지고있음)

	public Integer getAge() {
		 //현재 년도 구하기
		 Calendar now = Calendar.getInstance(); //년월일시분초
		 Integer currentYear = now.get(Calendar.YEAR);
		 
		 //태어난년도를 위한 세팅
		 SimpleDateFormat format = new SimpleDateFormat("yyyy");
		 String stringBirthYear = format.format(student_birthdate); //년도만받기
		 //태어난 년도
		 Integer birthYear = Integer.parseInt(stringBirthYear);

		 // 현재 년도 - 태어난 년도 => 나이 (만나이X)		 
		return (currentYear - birthYear +1);
	}

해당 메소드를 jsp에서 (테이블형식<td></td> 안에 값으로)쓸 때

<td>${list.getAge()}</td>

 

mapper에 나이에 대한 속성이 없을때 검색기능

	<select id="getStudentList" resultType="kr.~~~.~~~.vo.StudentVO">
		select * from student
			where teacher_student_id = #{userInfo.teacher_id}
 			<if test="cri.searchType != 2 and cri.searchType !=3 and cri.searchType !=4">
 				and (student_name like concat('%', #{cri.search}, '%')
 				or year(now()) - year(student_birthdate) +1 = #{cri.search}
 				or student_gender like concat('%', #{cri.search}, '%')
 				or student_school like concat('%', #{cri.search}, '%'))
 			</if>
 			<if test="cri.searchType == 2">
 				and (student_name like concat('%', #{cri.search}, '%')
 				or year(now()) - year(student_birthdate) +1 = #{cri.search})
 			</if>
 			<if test="cri.searchType == 3"> 
 				and student_gender like concat('%', #{cri.search}, '%')
 			</if>
 			<if test="cri.searchType == 4"> 
				and student_school like concat('%', #{cri.search}, '%')
 			</if>
			order by student_name asc;
	</select>

해당 코드로 나이를 계산할 수 있게됨. #{cri.search}는 검색어를 말함

or year(now()) - year(student_birthdate) +1 = #{cri.search}

 

에러1

혹시라도 mapper에 ${cri.search}부분이 ??? 이런식으로 에러가 난다면

if문안에 and ( 쓰면서 열린 소괄호를 ) 로 닫아주지 않아서 일 수 있는 가능성이 있음 => 내실수눈물

 

 

한국식 나이 계산법
(현재년도 - 태어난년도 + 1)
예: year(now()) - year('2001-03-02') +1 = 한국식나이

만 나이 계산법(대충) // (주의* 생일에 따라 만나이가 +1 되는 시점은 따로 코드를 적어서 해줄 것)
(현재년도 - 태어난년도)

만나이
SELECT FLOOR((CAST(REPLACE(CURRENT_DATE,'-','') AS UNSIGNED) - CAST('19931124' AS UNSIGNED)) / 10000);

 

 

 

도움이됐던 내용들이 있는 출처: 

참고한블로그

참고한 댓글

참고한블로그2