我有一个实体,其字段如下:
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
@Column(nullable = false)
private LocalDateTime lastActivity;我的表单有以下字段:
<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>在显示表单和创建新实体之前,在发送到表单页之前,我手动为该字段分配一个新值,如下所示:
entity.setLastActivity(LocalDateTime.now());表单中的字段正确显示2020-01-21 09:16:53,但当将表单发回时,我得到以下错误:
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注释就足够了。这显然是有效的,因为如果我删除它,我就会得到一个日期,当表单显示时,该字段的格式是不同的。我尝试添加以下转换器,但仍然得到相同的错误:
@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"));
}
}我做错了什么?
发布于 2020-01-21 19:37:57
我发现了问题,正确的DateTimeFormat是yyyy:mm:ss,注意大写HH。顺便说一句,不需要转换器,@DateTimeFormat注释会处理这一切!
https://stackoverflow.com/questions/59843532
复制相似问题