java日期时间格式化@JsonFormat与@DateTimeFormat的使用

Fawziya ·
更新时间:2024-09-20
· 1516 次阅读

如果要使用 @JsonFormat 这个注解的话,需要在项目中添加 jackson 相关的依赖包;

因为 @JsonFormat 注解不是 Spring 自带的注解,所以使用该注解前需要添加 jackson 相关的依赖包。当然,如果是 SpringBoot 项目就不需要自己手动添加依赖了,因为在 spring-boot-start-web 下已经包含了 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>

大家可以去这个网站搜索想要的依赖:https://mvnrepository.com

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
将后端返回给前端的日期时间进行格式化,pattern为转换后的格式,timezone为日期时间的时区
默认情况下timeZone为GMT(即标准时区),而北京是在东八区,所以会造成差8小时
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别

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

@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
将前端传给后端的日期时间进行格式化,pattern为转换后的格式

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime userCreateDate;

POST请求,我们一般会用@RequestBody接收JSON对象,如果对象里面有日期时间类型数据的话,我们可以使用 @JsonFormat注解进行格式化,它既可以对出参进行格式化,也可以对入参进行格式化

GET请求参数都是拼接在URL后面的,则需要使用@DateTimeFormat对入参进行格式化,放到@RequestBody修饰的对象里面是无效的

@JsonFormat是格式化json格式的。
@DateTimeFormat是格式化 key=value 这种格式的。

需要取数据到前台,也需要前台数据传到后台,都需要进行时间格式的转换,可以同时使用

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

SpringBoot的配置文件

application.yml

spring: # Content-Type 为 application/json, @JsonFormat(优先级高) 或 spring.jackson.date-format jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 # Content-Type 为 application/x-www-form-urlencoded(普通表单上传)spring.mvc.date-format(优先级高) 或 @DatetimeFormat mvc: format: date-time: yyyy-MM-dd HH:mm:ss

application.properties

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.indent_output=true spring.jackson.serialization.fail_on_empty_beans=false

到此这篇关于java日期时间格式化@JsonFormat与@DateTimeFormat的使用的文章就介绍到这了,更多相关java @JsonFormat与@DateTimeFormat内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



jsonformat JAVA 格式化

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章