这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战
最近看到一些介绍这两个注解的帖子,有一些说的不够准确,所以在此记录一下
如果要使用 @JsonFormat 这个注解的话,需要在项目中添加 jackson 相关的依赖包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
如果要使用 @DateTimeFormat 这个注解的话,需要在项目中添加 springframework 相关的依赖包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
注:SpringBoot的 spring-boot-start-web 下已经包含了jackson的相关依赖,spring-boot-starter-freemarker 下已经包含了springframework的相关依赖,不需要额外添加,我这里使用的开发工具是idea,使用Maven Helper这个插件可以看pom依赖关系树
- Maven Helper 插件
- 使用Maven Helper查看依赖关系树 jackson
springframework
大家可以去这个网站搜索想要的依赖:mvnrepository.com
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime userCreateDate;
将后端返回给前端的日期时间进行格式化,pattern为转换后的格式,timezone为日期时间的时区
在国内默认时区使用的是CST时区,两者相差8小时,这里时区为设置时区为上海时区
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime userCreateDate;
将前端传给后端的日期时间进行格式化,pattern为转换后的格式
总结
POST请求,我们一般会用@RequestBody接收JSON对象,如果对象里面有日期时间类型数据的话,我们可以使用 @JsonFormat 注解进行格式化,它既可以对出参进行格式化,也可以对入参进行格式化
GET请求参数都是拼接在URL后面的,则需要使用@DateTimeFormat对入参进行格式化,放到@RequestBody修饰的对象里面是无效的