In my Spring Boot application, I need to handle a form with date time field and convert it to LocalDateTime
in Java.
I specified pattern "YYYY-MM-dd HH:mm"
and it fails to convert when I submit the form with input value 1990-01-01 10:10
.
Here is the form object:
public class UserForm {
@NotNull
@DateTimeFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime dateTime;
// getters, setters
}
Controller:
@RequestMapping("/users")
@Controller
public class UserController {
@GetMapping("")
public String userForm(UserForm userForm) {
return "/users/form";
}
@PostMapping("")
public String postForm(@Valid UserForm userForm, BindingResult bindingResult) {
System.out.println(userForm + " " + bindingResult);
return "/users/form";
}
}
And Thymeleaf form:
<form th:object="${userForm}" th:action="@{/users}" method="post">
<span th:each="err: ${#fields.errors('dateTime')}" th:text="${err}" style="background-color:red;color:white;"/>
<input type="text" th:field="*{dateTime}"/>
<input type="submit">
</form>
What is wrong with this example ? How should I fix it to make it properly parse String
to LocalDateTime
?
I also submitted example application here.
Update:
Under "fails to convert" I mean I'm getting exception:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.NotNull @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value 1990-01-01 10:10
Using lowercase
yyyy
fixed the problem. Thanks.