DateTimeFormat和JsonFormat使用案例

DateTimeFormat和JsonFormat使用案例

基础入参对象

1
2
3
4
@Data
public class DemoNoAnnotation {
private Date nowTime;
}
1
2
3
4
5
@Data
public class DemoWithAnnotation {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}
1
2
3
4
5
6
@Data
public class DemoWithResponse {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date nowTime;
}
1
2
3
4
5
@Data
public class DemoOnlyResponse {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date nowTime;
}

case1:

1
2
3
4
@PostMapping("/testZero")
public DemoNoAnnotation testZero(DemoNoAnnotation demoTest) {
return demoTest;
}

image-20231122115825602

image-20231122115842780

post方式,form-data传参,方法入参没有添加@ResponseBody。

这种情况下,只接受 格式为 yyyy/MM/dd HH:mm:ss 的时间参数。

case2:

1
2
3
4
@PostMapping("/testOne")
public DemoWithAnnotation testOne(DemoWithAnnotation demoWithAnnotation) {
return demoWithAnnotation;
}

image-20231122131947734

image-20231122132004890

post, form-data,没有@ResponseBody,有@DateTimeFormat注解

时间的入参格式必须和注解上的一致才可以。

case3:

1
2
3
4
@PostMapping("/testTwo")
public DemoWithAnnotation testTwo(DemoWithAnnotation demoWithAnnotation) {
return demoWithAnnotation;
}

image-20231122132158721

image-20231122132209806

post, json 传参,没有@ResponseBody注解,标有@DateTimeFormat注解

无论是否按照@DateTimeFormat注解的格式进行传参,服务器都不会进行转换这个参数。

case4:

1
2
3
4
5
@PostMapping("/testThree")
public DemoWithAnnotation testThree(@RequestBody DemoWithAnnotation demoWithAnnotation) {
System.out.println("demoTest = " + demoWithAnnotation);
return demoWithAnnotation;
}

image-20231122132456320

image-20231122132508332

image-20231122132529889

有@ResponseBody注解,有@DateTimeFormat注解,post,json

这个时候,@DateTimeFormat注解其实是失效的。前面的两个方式报错,是因为@ResponseBody在尝试解析这个参数,但是解析失败了。

这个时候,默认接受的时间格式是:ISO8601 的时间格式:

yyyy-MM-dd’T’HH:mm:ss.SSSXXX

yyyy-MM-dd’T’HH:mm:ss.SSSXX

yyyy-MM-dd’T’HH:mm:ss.SSSX

也就是:

2023-11-22T02:47:39.003+08:00

2023-11-22T02:47:39.003+0800

2023-11-22T02:47:39.003+08

img

case5:

1
2
3
4
5
@PostMapping("/testFour")
public DemoWithResponse testFour(@RequestBody DemoWithResponse demoTest) {
System.out.println("demoTest = " + demoTest);
return demoTest;
}

image-20231122132955811

有@ResponseBody返回值的参数是正确解析了的。

case6:

1
2
3
4
5
@PostMapping("/testFive")
public DemoWithResponse testFive(DemoWithResponse demoTest) {
System.out.println("demoTest = " + demoTest);
return demoTest;
}

image-20231122133155945

没有@ResponseBody返回值的参数也是正确解析了的。

case7:

1
2
3
4
5
@PostMapping("/testSix")
public DemoOnlyResponse testSix(@RequestBody DemoOnlyResponse demoTest) {
System.out.println("demoTest = " + demoTest);
return demoTest;
}

image-20231122134514998

仅有@JsonFormat的话,也可以实现入参与出参的格式化。

使用@RequestBody 接受json参数时,如果不配置自定义格式的话,默认使用的格式是yyyy-MM-dd’T’HH:mm:ss.SSSZ。这个传入的参数也可以比默认的格式减少字段,比如实际传入:2025-01-01T14:22


参考链接

https://zhuanlan.zhihu.com/p/382657475