@JsonFormat @DataTimeFormat 时间格式
创始人
2024-05-30 19:56:06
0次

省流:用@JsonFormat即可

有时候会看到入参dto里,在时间类型的变量上用@DateTimeFormat,代码如下。

public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")private Date startDate;
}

这是为了入参传日期格式的值。即前端给后端传日期,如 {"startDate":"2022-01-01 01:02:02"}。如果没有@DateTimeFormat,会报错。

Invalid JSON input: 
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); 
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: 
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))

根据报错信息,while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',传入的值日期格式有问题。正确格式:2023-02-01T00:00:00.000+0800,即前端传参 {"startDate":"2023-02-01T00:00:00.000+0800"}。

所以有人会用@DataTimeFormat。

但@DataTimeFormat不如@JsonFormat好用。另,如果值是纯日期,例如2022-01-01,不需要用注解。

@DataTimeFormat用于前端传后端,@JsonFormat用于后端传前端,这种说法是错误的。@JsonFormat前传后、后传前都可以用。

@JsonFormat

com.fasterxml.jackson.annotation.JsonFormat;

public class XXXdto{@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date startDate;
}

@DataTimeFormat

org.springframework.format.annotation.DateTimeFormat

public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date startDate;
}

@JsonFormat 和 @DateTimeFormat 区别

@JsonFormat

@DateTimeFormat

转换前端传入后端的时间格式的值

√

√

约束后端响应前端的时间类型的值

√

×

数据类型(前端提交到后端)

必须json

用@RequestBody

必须form表单

不用@RequestBody

时区

√

×

响应给前端的时间会比实际时间晚8个小时

补充:

1.前端传值给后端,后端接收到的都是字符串。

2.前端传日期格式的值,如果形如yyyy-MM-dd,即{"startDate":"2023-01-02"},不需要用@DataTimeFormat和@JsonFormat,框架会帮你转。

参考

不要在听大坑们@DateTimeFormat 和 @JsonFormat只是前后端传参的区别了_*阿莫西林*的博客-CSDN博客

SpringBoot中时间格式化的5种方法!

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...