pooney
Published 2020. 4. 27. 03:49
Spring @DateTimeFormat Spring

프론트에서 날짜를 Controller에게 넘겨야 할때가 있다. 이때 날짜 형식이 text인경우가 존재하는데 이경우 타입에러가 발생한다. String 형태로 들어온 값을 Date로 변환하지 못했기 때문이다. 이떄 @DateTimeFormat 를 사용하여 원하는 패턴으로 변경하여 저장 할 수가 있다. 

 

 

 

1. 날짜가 String 으로 Controller로 이동 

<input type="text" id="datePicker" class="form-control" value="종료시간 선택" name="endDay">

 

 

2.  String 형태로 들어온 값을 Date로 변환하지 못했기 때문에 에러가 발생한다.

 

TeamDTO(변경 전)

public class TeamDTO {
	private Date endDay; //마감시간;
}

 

 

에러

WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teamDTO' on field 'endDay': rejected value [2020-04-29]; codes [typeMismatch.teamDTO.endDay,typeMismatch.endDay,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teamDTO.endDay,endDay]; arguments []; default message [endDay]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endDay'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-04-29'; nested exception is java.lang.IllegalArgumentException]]

 

3. @DateTimeFormat 을 사용하여 값을 저장한다. 

 

TeamDTO(변경 후)

public class TeamDTO {
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private Date endDay; //마감시간;
}

 

 

profile

pooney

@pooney

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!