0

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?

ltsstar
  • 832
  • 1
  • 8
  • 24
  • Did you try using the double brace syntax (`{{ ... }}`)? See http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#double-brace-syntax. – Hidde May 07 '17 at 17:09
  • I didn't pursue the initbinder approach, but you made me curious and I tried it out and noticed that Thymeleaf now uses it's own time format (dd.MM.yy HH:mm). It's still not using my initbinder though. – ltsstar May 09 '17 at 09:23

1 Answers1

0

remove the parameter"reservationtime", may resolve the issue :

binder.registerCustomEditor(LocalDateTime.class, new LocalDateTimeEditor());

And Then, the converter will be used for ALL LocalDateTime fields

zmekni
  • 1