- 更新:这甚至不是一个问题,这完全是我的DUMB。请投票反对这个问题。**
感谢@M Deinum指出,这不是一个Spring的事情。
我的IDEA的设置在今天早上的一次崩溃中搞砸了,并且在重新运行之前没有自动编译。
控制器
@GetMapping("/page")
public Response Page(@ParameterObject Page page, @ParameterObject QueryDTO param) {
/*
* irrelevant parts omitted
*/
}
当我在DTO中使用它时,它可以很好地处理传入的yyyy-MM-dd'T'HH:mm:ss
模式。
@Data
public class QueryDTO {
/*
* irrelevant parts omitted
*/
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime startTime;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime endTime;
}
但是当我想用“”而不是“T”时,我试过:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
并将输入参数从“1999 - 02 - 11T00:00:00”更改为“1999 - 02 - 11 00:00:00”,我得到endTime Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'endTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value [1999-02-11 00:00:00]; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [1999-02-11 00:00:00]
有没有使用注解而不是手动编写转换器的解决方案?
非常感谢。
我试着用关键字“LocalDateTime@ParameterObject@DateTimeFormat模式”搜索,没有得到太多帮助。
1条答案
按热度按时间06odsfpq1#
@DateTimeFormat
注解通常用于在Spring MVC
控制器中绑定请求参数时格式化和解析日期时间值。但是,它不支持直接使用空格的自定义模式。要实现指定的模式,您可以使用
@DateTimeFormat
注解和模式,也可以使用@InitBinder
。@DateTimeFormat
注解。如果您想直接在annotation中应用模式,而不需要全局配置,可以使用其他方法:
QueryDTO
类中使用它。然后,您可以编写一个自定义的Converter
,使用指定的模式将注解字符串转换为LocalDateTime
对象**。请让我知道它是否解决了你的问题,如果是的话,请留下你的意见。^^