我有一个关于 Spring + Thymeleaf 日期格式的问题。
我有一个带有 LocalDate 日期
字段的简单实体。我想从表单中的用户那里获取这个日期并将其保存到 MySQL 数据库中。
我收到这样的错误:
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
我的实体:
@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 action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">
<p>Date: <input type="date" th:field="*{date}" /></p>
</form>
出现这个问题的原因是什么?也许还有其他更好的存储日期的方法?
最佳答案
问题解决了.. 我不知道为什么,但将我的模板更改为:
<input type="date" th:value="*{date}" th:field="*{date}" />
并将 @DateTimeFormat(pattern = "yyyy-MM-dd")
添加到实体字段解决了这个问题。
关于java - 表单中的 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079923/