首页 文章

无法解析Spring控制器中的本地日期时间

提问于
浏览
0

在我的Spring Boot应用程序中,我需要处理一个带有日期时间字段的表单,并将其转换为Java中的 LocalDateTime .

我指定了模式 "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
}

控制器:

@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";
    }
}

和Thymeleaf形式:

<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>

这个例子有什么问题?我该如何解决它以使其正确解析 StringLocalDateTime

我还提交了example application here .

Update:

  • 在“无法转换”下我的意思是我得到例外:

org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[@javax.validation.constraints.NotNull @ org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] Value 1990-01-01 10:10

  • 使用小写 yyyy 修复了问题 . 谢谢 .

1 回答

  • 2

    日历年,而不是基于工作日的年份

    格式化模式应为 uuuu-MM-dd HH:mm .

    LocalDateTime.parse( 
        "1990-01-01 10:10" , 
        DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" )
    )
    

    大写 YYYY 表示基于周的年份而不是日历年 .

    更仔细地研究类文档以格式化模式代码 . 注意它们是区分大小写的 .

    ISO 8601

    提示:不使用自定义格式,而是坚持使用标准ISO 8601格式 .

    默认情况下,java.time类使用标准格式 . 所以不需要为指定格式化模式而烦恼 .

    LocalDateTime.parse( 
        "1990-01-01T10:10"
    )
    

    关于java.time

    java.time框架内置于Java 8及更高版本中 . 这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat .

    现在位于maintenance modeJoda-Time项目建议迁移到java.time类 .

    要了解更多信息,请参阅Oracle Tutorial . 并搜索Stack Overflow以获取许多示例和解释 . 规格是JSR 310 .

    您可以直接与数据库交换java.time对象 . 使用JDBC driver符合JDBC 4.2或更高版本 . 不需要字符串,不需要 java.sql.* 类 .

    从哪里获取java.time类?

    ThreeTen-Extra项目使用其他类扩展java.time . 该项目是未来可能添加到java.time的试验场 . 您可以在此处找到一些有用的类,例如IntervalYearWeekYearQuartermore .

相关问题