我正在尝试以Thymeleafe形式存储LocalDateTime,但是没有成功。我现在拥有的是:

模型:

public class Example{
    ...
    private LocalDateTime creationDate;
    ...


控制器:

@PostMapping("/saveExample")
public String saveOrUpdate(@Valid @ModelAttribute("example") Example example, BindingResult bindingResult) {


形成:

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


我得到的错误:

[Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'creationDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalDateTime] for value '2020-01-17'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-01-17]]


我尝试了很多与Google不同的解决方案,但是没有运气。有什么建议?
最好的祝福。

最佳答案

似乎您正在尝试解析值“ 2020-01-17”,但这对于LocalDateTime类而言不是有效值。

可能的解决方案:


在模型类中使用LocalDate而不是LocalDateTime
在模型类中使用String而不是LocalDateTime,然后(例如,在某些服务类中)使用自己的DateTimeFormatter解析String值:


    DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
        .toFormatter();

    LocalDateTime time = LocalDateTime.parse("2020-01-17", formatter);

关于java - 正确的Thymeleaf输入表单可存储LocalDateTime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59688532/

10-13 01:15