API에서 날짜타입의 값을 받아야 하는 경우가 은근있는데
날짜 처리가 잘 안되는 경우가 많았다.
Date, LocalDate, LocalDateTime
"Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'
해결방법 1.
@DateTimeFormat 사용하기
@GetMapping("/aaa")
public List<Dto> getDtos(
@RequestParam(defaultValue = "0") Integer offset,
@RequestParam(defaultValue = "50") Integer limit,
@RequestParam(name = "startDt", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startDt,
@RequestParam(name = "endDt", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDt) {
..........
}
해결방법 2.
현재 feign을 쓰고 있기 때문에...client 쪽 Configuration에
FeignFormatterRegistrar 로 bean을 등록해서 Date 타입으로 들어오는 경우에 fomatter를 추가하였다.
@Bean
public FeignFormatterRegistrar localDateFeignFormatterRegistrar() {
return formatterRegistry -> formatterRegistry.addFormatter(new Formatter<Date>() {
DateFormat formatter = new StdDateFormat();
@Override
public Date parse(String text, Locale locale) throws ParseException {
return formatter.parse(text);
}
@Override
public String print(Date object, Locale locale) {
return formatter.format(object);
}
});
}