I want to pass a LocalDateTime object to thymeleaf with a specific format (yyyy/MM/dd HH:mm) and later receive it back into my controller class. I want to use an customEditor / initbinder to do the convertion.
/**
* Custom Initbinder makes LocalDateTime working with javascript
*/
@InitBinder
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, "reservationtime", new LocalDateTimeEditor());
}
public class LocalDateTimeEditor extends PropertyEditorSupport {
// Converts a String to a LocalDateTime (when submitting form)
@Override
public void setAsText(String text) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(text, formatter);
this.setValue(localDateTime);
}
// Converts a LocalDateTime to a String (when displaying form)
@Override
public String getAsText() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
String time = ((LocalDateTime)getValue()).format(formatter);
return time;
}
}
While spring uses my initbinder when it receives the data from the form, thymeleaf though seems to prefer the .toString() method over my initbinder and my getAsText() method never gets called.
My view:
<input type="text" th:name="${reservationtime}" id="reservationtime" class="form-control"
th:value="${reservationtime}"/>
I find the initbinder "way" quite good in terms of code readability. So I would like to keep using the initbinder. Is it possible to tell thymeleaf to use my initbinder or any other good workaround?