괴발개발/Spring Framework

에러: Cannot invoke "java.util.Date.getTime()" because "date" is null

moonday 2021. 9. 11. 03:42

VO에서 나이를 계산하는 메소드를 넣어뒀는데, 매개변수를 넣어주지않고

VO에 있는 변수를 안에 고정으로 계산하게끔 넣어뒀더니

문제 : 해당메소드가 있는구역은 매개변수가 null이더라도 작동하기때문에 nullpointerexception이 발생.

원인 : null인 것을가지고 변환하거나 실행처리를해야하니까 에러남

해결 : 아래의 메소드안에 null일 때 값을 어떻게 처리할 것인지 코드를 넣어줬음 if(매개변수가 == null){return;}

 

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

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