I have an entity with the following field :
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
@Column(nullable = false)
private LocalDateTime lastActivity;
My form has the following field :
<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>
Prior to displaying the form and given the creation of a new entity, I manually assign that field a new value prior to sending to the form page like so :
entity.setLastActivity(LocalDateTime.now());
The field in my form correctly displays 2020-01-21 09:16:53 but when sending the form back I get the following error :
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]
I have the Java8TimeDialect correctly added to Thymeleaf (I have other pages using #temporal) and it was functional up to this moment. I was under the impression that the @DateTimeFormat annotation on the entity's field was sufficient. It clearly works because if I remove it i get a date that is formatted differently in that field when the form displays. I tried adding the following converter and I'm still getting the same error :
@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"));
}
}
What am I doing wrong?
I found the issue, the correct DateTimeFormat is yyyy-MM-dd HH:mm:ss, notice the capital HH. No converter is needed by the way, the @DateTimeFormat annotation takes care of it all!