Spring change date input format
jakarta-ee, spring, spring-mvc
Solution
Thanks to Tomasz I got the answer, I have to add a binder method to the controller:
@InitBinder
public void binder(WebDataBinder binder) {binder.registerCustomEditor(Timestamp.class,
new PropertyEditorSupport() {
public void setAsText(String value) {
try {
Date parsedDate = new SimpleDateFormat("dd.MM.yyyy HH:mm").parse(value);
setValue(new Timestamp(parsedDate.getTime()));
} catch (ParseException e) {
setValue(null);
}
}
});
}
Problem
I am trying to create a form, that will send back an object with a timestamp. Right now, the input format must be `yyyy-MM-dd HH:mm:ss`, I want the timestamp to be entered in the format `dd.MM.yyyy HH:mm` - how can I change the input format? The object class: ``` public class Test { private Timestamp dateStart; public Timestamp getDateStart() { return dateStart; } public void setDateStart(Timestamp dateStart) { this.dateStart = new Timestamp(dateStart.getTime()); } } ``` The controller method: ``` @RequestMapping(value="test", method = RequestMethod.POST) public View newTest(@ModelAttribute("test") Test test, Model model) { //save the Test object } ``` The jsp form: ``` <form:form action="service/test" method="post" modelAttribute="test"> <form:input type="text" path="dateStart" /> </form:form> ``` I get this error, when the format isn't right: ``` Field error in object 'test' on field 'dateStart': rejected value [22.05.2012 14:00]; codes [typeMismatch.test.dateStart,typeMismatch.dateStart,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [test.dateStart,dateStart]; arguments []; default message [dateStart]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'dateStart'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "22.05.2012 14:00" from type 'java.lang.String' to type 'java.sql.Timestamp'; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]] ```