LocalDate in the form

I have a question about Spring + Thymeleaf date format. I have a simple object with a field LocalDate date. I want to get this date from a user in a form and save it in a MySQL database. I get this error:

Failed to convert property value of type java.lang.String to the required type java.time.LocalDate for the date of the property; The nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to input java.time.LocalDate for value 2019-04-30; inested exception is java.time.format.DateTimeParseException: text 2019-04-30 cannot be parsed with index 2

My essence:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields

Type / form of thimeleaf:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">    
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>

What is the cause of this problem? Maybe there is another, better way to store the date?

+4
3

. , :

<input type="date" th:value="*{date}" th:field="*{date}" />

@DateTimeFormat(pattern = "yyyy-MM-dd") .

+5

, , LocalDate . :

@InitBinder
protected void initBinder(WebDataBinder binder) {
  binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
    @Override
    public void setAsText(String text) throws IllegalArgumentException{
      setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

    @Override
    public String getAsText() throws IllegalArgumentException {
      return DateTimeFormatter.ofPattern("yyyy-MM-dd").format((LocalDate) getValue());
    }
  });
}

, ControllerAdvice .

+1

Thymeleaf provides an additional module for this: https://github.com/thymeleaf/thymeleaf-extras-java8time

Adding the following dependency (maven) should be enough:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
+1
source

Source: https://habr.com/ru/post/1673441/


All Articles