Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate in form

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

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

@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

Thymeleaf view / form:

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

What's the reason for this problem? Maybe there is the other, better way to storage date?

like image 568
crooked Avatar asked Mar 28 '17 21:03

crooked


2 Answers

Problem solved.. I don't know why but changing my template to:

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

and adding @DateTimeFormat(pattern = "yyyy-MM-dd") to entity field solved the problem.

like image 52
crooked Avatar answered Sep 20 '22 11:09

crooked


Thymeleaf provides an extra module for that: 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>
like image 43
Tommy Schmidt Avatar answered Sep 23 '22 11:09

Tommy Schmidt