首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ConversionFailedException + Thymeleaf LocalDateTime

ConversionFailedException + Thymeleaf LocalDateTime
EN

Stack Overflow用户
提问于 2020-01-21 14:42:46
回答 1查看 290关注 0票数 0

我有一个实体,其字段如下:

代码语言:javascript
复制
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
@Column(nullable = false)
private LocalDateTime lastActivity;

我的表单有以下字段:

代码语言:javascript
复制
<div class="form-group">
    <div class="input-group date dateTimePicker" id="datetimepicker17" data-target-input="nearest">
        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker17" id="lastActivity" th:field="*{lastActivity}"/>
        <div class="input-group-append" data-target="#datetimepicker17" data-toggle="datetimepicker">
            <div class="input-group-text"><i class="fa fa-calendar"></i></div>
        </div>
        <label class="errorMessage" th:if="${#fields.hasErrors('lastActivity')}" th:errors="*{lastActivity}">Last Activity Error</label>
    </div>
</div>

在显示表单和创建新实体之前,在发送到表单页之前,我手动为该字段分配一个新值,如下所示:

代码语言:javascript
复制
entity.setLastActivity(LocalDateTime.now());

表单中的字段正确显示2020-01-21 09:16:53,但当将表单发回时,我得到以下错误:

代码语言:javascript
复制
Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime for property lastActivity; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat @javax.persistence.Column java.time.LocalDateTime] for value 2020-01-21 09:16:53; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-01-21 09:16:53]

我已经正确地将Java8TimeDialect添加到Thymeleaf (我有其他页面使用#temporal),直到现在它才开始工作。我的印象是,实体字段上的@DateTimeFormat注释就足够了。这显然是有效的,因为如果我删除它,我就会得到一个日期,当表单显示时,该字段的格式是不同的。我尝试添加以下转换器,但仍然得到相同的错误:

代码语言:javascript
复制
@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime>
{
    @Override
    public LocalDateTime convert(String source) 
    {
        return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
    }
}

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-21 19:37:57

我发现了问题,正确的DateTimeFormat是yyyy:mm:ss,注意大写HH。顺便说一句,不需要转换器,@DateTimeFormat注释会处理这一切!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59843532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档