Java 带LocalDateTime问题的Spring-terymeleaf
我在使用Spring和Thymeleaf的localdatetime属性时遇到问题 我的代码: Event.javaJava 带LocalDateTime问题的Spring-terymeleaf,java,spring,spring-boot,datetime,thymeleaf,Java,Spring,Spring Boot,Datetime,Thymeleaf,我在使用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 S
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>
为什么会这样?仔细看看:
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**
提供的时间为:2014年5月14日。下午1:00
您需要相应地更改代码以支持AM/PM:
尝试:
及
此处a表示上午或下午
更多信息请查看此处:您的字符串包含模式中不存在的AM/PM现在我得到了相同的异常,但值为:2019-05-29T09:27;我还尝试将模式中的小时字母从“HH”改为“HH”,就像你给我的链接中解释的那样(谢谢你,顺便说一句,这在理解方面非常有帮助),但结果是“2019-05-29T09:27”,这与定义的“MM.dd.yyyy.HH:MM a”不同。因此,预计会出现例外情况。您的应用程序是否必须支持多种不同的时间格式?不,它不必支持;已尝试将格式更改为“yyyy.MM.dd.hh:MM a”,但与我上面的注释中的值相同的异常…请参阅“2019-05-29T09:27”值与定义的“yyyy.MM.dd.hh:MM a”也不匹配。尝试将“2019-05-29T09:27”更改为“yyyy-MM-dd'T'HH:MM”=>仍然不走运;我已经了解到HTML datetime本地元素还没有在所有浏览器中得到完全支持,因此我将尝试另一种方法,分别使用日期和时间元素,但感谢您尝试解决我的问题
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 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,