@DateTimeFormat确实仅适用于受限模式为什么会发生?

问题描述

我正在制作一个接收两个注册日期的表格,以查找在插入日期之间注册的用途的列表。

要将表单中的输入绑定到Command实例的类型LocalDateTime的数据,我在命令实例中使用了@DateTimeFormat注释,但是此代码中仅一种模式有效。 / p>

只有yyyyMMddHH模式可以正常工作。 yyyy-MM-ddyyyy/MM/dd等其他模式无效。

他们抛出类似以下的异常

无法将类型java.lang.String的属性值转换为所需的属性类型java.time.LocalDateTime;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[@ org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime],其值为2020-08- 13;嵌套异常是java.lang.IllegalArgumentException:解析尝试失败,值[2020-08-13]

这是命令实例的代码,

public class UserSearchByRegDateRequest {
    
    @DateTimeFormat(pattern = "yyyyMMddHH")
    private LocalDateTime from;
    @DateTimeFormat(pattern = "yyyyMMddHH")
    private LocalDateTime to;
    
    public LocalDateTime getFrom() {
        return from;
    }
    public void setFrom(LocalDateTime from) {
        this.from = from;
    }
    public LocalDateTime getTo() {
        return to;
    }
    public void setTo(LocalDateTime to) {
        this.to = to;
    }
}

表格代码

<body>

    <h2><spring:message code="regDateSearchFormTitle"/></h2>
    
    <spring:message code="dateFormatInstruction"/><br/><br/>
    
    <form:form action="processSearch" modelAttribute="searchCommand">
        
        <label> 
            <form:input path="from"/><spring:message code="from"/>
            <form:errors path="from"/>
        </label>
            
        <label>
            <form:input path="to"/><spring:message code="to"/>
            <form:errors path="to"/>
        </label>
            
        <input type="submit" value="search"/>
    </form:form>
    
    <c:if test="${!empty members}">
        <table>
            <tr>
                <th><spring:message code="search.id"/></th>
                <th><spring:message code="search.name"/></th>
                <th><spring:message code="search.email"/></th>
                <th><spring:message code="search.regDate"/></th>
            </tr>

        <c:forEach var="member" items="${members}">
            <tr>
                <td>${member.id}</td>
                <td>${member.name}</td>
                <td>${member.email}</td>
                <td><tf:formatDateTime value="${member.registerDateTime}" pattern="yyyy-MM-dd"/></td>
            </tr>
        </c:forEach>
        
        </table>
    </c:if>
</body>

解决方法

由于您仅尝试转换日期“ 2020-08-13”而不指定时间,因此应使用具有以下格式的LocalDate:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate from;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate to;

然后可以将格式为“ 2020-08-13”的字符串转换为LocalDate,而不会引发异常。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...