Ole*_*han 0 java validation spring datetime-format spring-boot
在我的 Spring Boot 应用程序中,我需要处理带有日期时间字段的表单并将其转换为LocalDateTimeJava 格式。
我指定了模式"YYYY-MM-dd HH:mm",但当我提交带有输入值的表单时,它无法转换1990-01-01 10:10。
这是表单对象:
public class UserForm {
@NotNull
@DateTimeFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime dateTime;
// getters, setters
}
Run Code Online (Sandbox Code Playgroud)
控制器:
@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";
}
}
Run Code Online (Sandbox Code Playgroud)
和百里香形式:
<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>
Run Code Online (Sandbox Code Playgroud)
这个例子有什么问题吗?我应该如何修复它以使其正确String解析LocalDateTime?
我还在这里提交了示例应用程序。
更新:
在“无法转换”下,我的意思是我遇到了异常:
org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [@javax.validation.constraints.NotNull @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime]值 1990-01-01 10:10
使用小写yyyy解决了这个问题。谢谢。
格式化模式应该是uuuu-MM-dd HH:mm.
LocalDateTime.parse( \n "1990-01-01 10:10" , \n DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" )\n)\nRun Code Online (Sandbox Code Playgroud)\n\n大写字母YYYY表示基于周的年份而不是日历年。
更仔细地研究类文档以格式化模式代码。请注意它们是如何区分大小写的。
\n\n提示:不要使用自定义格式,而应坚持使用标准 ISO 8601 格式。
\n\njava.time类默认使用标准格式。因此无需费心指定格式模式。
\n\nLocalDateTime.parse( \n "1990-01-01T10:10"\n)\nRun Code Online (Sandbox Code Playgroud)\n\njava.time框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat。
Joda -Time项目现在处于维护模式,建议迁移到java.time类。
\n\n要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
\n\n您可以直接与数据库交换java.time对象。使用与JDBC 4.2或更高版本兼容的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
从哪里获取 java.time 类?
\n\nThreeTen -Extra项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如Interval、、、等等。YearWeekYearQuarter
| 归档时间: |
|
| 查看次数: |
2884 次 |
| 最近记录: |