我在使用Spring和Thymeleaf的localdatetime属性时遇到问题。
我的代码:
Event.java
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
@NotNull(message="Name is required!")
private String name;
@Column(nullable=false)
@NotNull(message="Time is required!")
@DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm")
private LocalDateTime time;
}
EventController.java
...
@GetMapping("/eventEntry")
public String showForm(Model model) {
model.addAttribute("event", new Event());
return "eventEntry";
}
@PostMapping("/eventEntry")
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm") LocalDateTime time,
@Valid Event event, Errors errors, Model model) {
if(errors.hasErrors()) {
return "eventEntry";
} else {
eventList.add(event);
eventRepository.save(event);
model.addAttribute("event", event);
model.addAttribute("time", time);
model.addAttribute("listaDogadaja", listaDogadaja);
return "output";
}
}
eventEntry.html
<body>
<h1>Event entry form</h1>
<h3>New event</h3>
<form method="POST" th:object="${event}">
<div class="form-group">
<label for="naziv">Name: </label>
<input type="text" th:field="*{name}" />
<span class="validation-error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
</div>
<div class="form-group">
<label for="time">Time: </label>
<input type="datetime-local" th:field="*{time}" />
<span class="validation-error" th:if="${#fields.hasErrors('time')}" th:errors="*{time}">Time Error</span>
</div>
<div class="form-group">
<input type="submit" th:value="Save">
<input type="reset" class="btn btn-danger" th:value="Cancel">
</div>
</form>
</body>
单击“保存”按钮时,出现此异常:
Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime';
nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '05.14.2014. 1:00 PM';
nested exception is
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**
那是为什么?
答案 0 :(得分:1)
仔细看看:
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**
提供的时间是: 2014年5月14日。 1:00 PM
您需要相应地更改代码以支持 AM / PM : 尝试:
...
@DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a")
private LocalDateTime time;
和
...
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a") LocalDateTime time,
此处 a 表示上午或下午。
更多信息请看这里:format-time-12-hours-pattern