前端get请求日期类型参数向后端传参失败

发布于:2024-05-08 ⋅ 阅读:(28) ⋅ 点赞:(0)

1、背景

get请求,通过url上传参,因此日期类型是string类型数据

2、异常信息

nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2011-02-01';
 nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2011-02-01]] 

3、解决方案

请求参数中添加

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

不能使用@JsonFormat

4、原因

  1. 注解@JsonFormat主要是后端到前端的时间格式的转换

  2. 注解@DateTimeFormat主要是前端到后端的时间格式的转换

  3. 这两者的注解一般联合使用

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date time;

      4.区别如下:

(1)@JsonFormat 是 Jackson 库中的注解,用于在序列化和反序列化过程中控制日期和时间的格式

该注解提供了一种自定义日期和时间格式的方式,以确保在 JSON 数据和 Java 对象之间正确地进行转换

(2)@DateTimeFormat 是 Spring 框架中用于处理日期和时间格式的注解。

它通常与 @RequestMapping、@RequestParam 等注解一起使用,以指定接收或发送日期时间参数时的格式。

以下是 @DateTimeFormat 注解的一些主要概念和功能:

pattern(模式): 通过 pattern 属性,您可以指定日期和时间的格式。
与 @JsonFormat 不同,@DateTimeFormat 是专门为 Spring 框架设计的,用于在 Web 请求中处理日期参数。

iso(ISO标准格式): 使用 iso 属性可以指定使用 ISO 标准的日期时间格式。
例如,@DateTimeFormat(iso = ISO.DATE) 表示日期部分采用标准日期格式。

style(样式): style 属性定义了预定义的日期和时间格式。
有三种样式可用:DEFAULT、SHORT、MEDIUM、LONG、FULL。这些样式在不同的地区设置下有不同的显示效果。

lenient(宽松解析): lenient 属性用于指定是否宽松解析日期。
如果设置为 true,则在解析日期时会尽量接受不严格符合格式的输入。

patternResolver(模式解析器): patternResolver 属性允许您指定自定义的模式解析器,以便更灵活地处理日期时间格式。