【问题标题】:Cannot parse local date time in Spring controller无法在 Spring 控制器中解析本地日期时间
【发布时间】:2018-07-16 20:33:04
【问题描述】:

在我的 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";
    }
}

和百里香形式:

<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

更新:

  • 在“转换失败”下,我的意思是我遇到了异常:

    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 解决了这个问题。谢谢。

【问题讨论】:

  • 定义“转换失败”。并使用正确的模式。 YYYY 是周年。你想要年份。年年。

标签: java spring validation spring-boot datetime-format


【解决方案1】:

日历年,而不是基于周的年

格式化模式应该是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

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

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

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2023-02-15
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多