Java 用于存储LocalDateTime的正确输入表单
我试图将LocalDateTime存储在Thymeleafe表单中,但没有成功。我现在所拥有的: 型号:Java 用于存储LocalDateTime的正确输入表单,java,model-view-controller,thymeleaf,Java,Model View Controller,Thymeleaf,我试图将LocalDateTime存储在Thymeleafe表单中,但没有成功。我现在所拥有的: 型号: public class Example{ ... private LocalDateTime creationDate; ... 控制器: @PostMapping("/saveExample") public String saveOrUpdate(@Valid @ModelAttribute("example") Example example, Bindin
public class Example{
...
private LocalDateTime creationDate;
...
控制器:
@PostMapping("/saveExample")
public String saveOrUpdate(@Valid @ModelAttribute("example") Example example, BindingResult bindingResult) {
表格:
我尝试了很多不同于谷歌的解决方案,但没有成功。有什么建议吗?
致以最诚挚的问候。看起来您正在尝试解析值“2020-01-17”,但它不是LocalDateTime类的有效值 可能的解决办法:
您需要向实体中的LocalDateTime字段添加
@DateTimeFormat
注释。例如:
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime creationDate;
在pom.xml中是否有
thymeleaf-extras-java8time
?你看到了哪些例外?是的,我的pom中有这种依赖关系。post中的错误消息。请看一下如何使用转换器
:
[Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'creationDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalDateTime] for value '2020-01-17'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-01-17]]
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
LocalDateTime time = LocalDateTime.parse("2020-01-17", formatter);
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime creationDate;