백앤드

java.time.format.DateTimeParseException: Text could not be parsed at index 0

머리큰개발자 2023. 2. 27. 22:58

오늘은 짜-증나는 exception을 겪었다.

 

프론트에서 연도와 월을 픽한 후 백으로 날리는 과정인데,

'yyyyMM'의 String으로 날려주고 있었다.

 

나는 당연히 LocalDateTime과 DateTimeFormatter를 사용하여 

String을 DateTime 형식으로 바꿔주려고 했으나

index0 오류 때문에 도저히 진행할 수가 없었다.

 

기존 실행했던 함수는 다음과 같다.


String frontDate="201212";
		
LocalDateTime localDateTime;
		
localDateTime = LocalDateTime.parse(frontDate, DateTimeFormatter.ofPattern("yyyyMM"));

당연히 에러가 났다.

Unable to obtain LocalDateTime from TemploralAccessor: {Year= 2012, MonthOfYear=12}, ISO of type...

간단히 말해서 파싱을 못하고 있었다.

 

LocalDateTime형식을 DateTimeFormatter에서 사용할 수 없기 때문이다.

 

그래서 LocalDate로 바꿔서 해봤다.

String frontDate="201212";
		
LocalDate localDate;
		
localDate = LocalDate.parse(frontDate, DateTimeFormatter.ofPattern("yyyyMM"));
		
System.out.println(localDate);

마찬가지이다.

 

최대한 간단한 방식을 쓰기로 했다.

내가 파악한 원인은 .ofPattern 메서드에서 최소 d 까지는 있어야 한다는 것이다.

그래서 그냥 date 어차피 월까지만 쓸 것이기 때문에

아무 요일이나 넣어놓고 잘라서 쓰기로 했다.

String frontDate="201212";
		
LocalDate localDate;
		
localDate = LocalDate.parse(frontDate.concat("01"), DateTimeFormatter.ofPattern("yyyyMMdd"));
		
System.out.println(localDate);

잘 나온다.

 

이제야 2년 전 월을 알 수 있었다..

String frontDate="201212";
		
		
System.out.println(
	LocalDate.parse(frontDate.concat("01"), 
		DateTimeFormatter
			.ofPattern("yyyyMMdd"))
			.minusYears(2)
            .format(DateTimeFormatter.ofPattern("yyyyMM")
    )
);