共计 2279 个字符,预计需要花费 6 分钟才能阅读完成。
目录
一、Spring 之 @JsonFormat 注解使用场景:将 Date 类型的默认时间格式通过序列化转换为我们想要的格式进行返回。
1、引入依赖 jackson 依赖,@JsonFormat 注解就在 jackson-annotations 包下,
2、如何使用 @JsonFormat 注解
二、Spring 之 @DateTimeFormat 注解使用场景:他是将前端提交传递给后端的字符串日期时间转换为 Date 类型进行进行功能操作。
1、引入 Spring 及 SpringMVC 依赖,若不是 SpringBoot 或 SpringCloud 最好将下方 Spring 相关的依赖整合起来,避免项目时存在的问题;
2、如何使用 @DateTimeFormat 注解
3、测试添加 @DateTimeFormat 注解效果,完美解决了参数传递类型转换问题。
如果不加 @DateTimeFormat 注解就报 400,参数类型无法传进接口,则不会响应:
三:这里还是聊下 Element-UI 的一个日期时间选择器差一天问题,之前在我整理的 @InitBinder 里面看过该功能的可以跳过,想了解 @InitBinder 进行日期转换的就点击该标题跳转去看下;
一、Spring 之 @JsonFormat 注解使用场景:将 Date 类型的默认时间格式通过序列化转换为我们想要的格式进行返回。
1、引入依赖 jackson 依赖,@JsonFormat 注解就在 jackson-annotations 包下,
如果是 SpringBoot、SpringCloud 在创建时都自动集成所以不用添加也可以,其他涉及 Spring 架构且并未自动集成的需要加 jackson 依赖;
com.fasterxml.jackson.core
jackson-annotations
2.9.6
com.fasterxml.jackson.core
jackson-core
2.9.6
com.fasterxml.jackson.core
jackson-databind
2.9.6
2、如何使用 @JsonFormat 注解
(1) 在属性上加上 @JsonFormat 注解;
(2) 参数 pattern:需要转换的日期格式,当然也可以“yyyy-MM-dd HH:mm:ss”;
(3)参数 timezone:@JsonFormat 注解使用的是标准的 GMT 时间,于北京时间差 8 小时,所以需要“GMT+8”来达到北京时间同步;
时区 (GMT) 简介:格林尼治标准时间(旧译格林威治平均时间或格林威治标准时间;英语:GreenwichMeanTime,GMT)是指位于英国伦敦郊区的皇家格林尼治天文台的标准时间,也是目前的协调世界时(UTC),与北京时间慢 8 个小时,所以需要(GMT+8)。
3、测试注解效果,上面是去掉注解的格式,下面是注解效果;
二、Spring 之 @DateTimeFormat 注解使用场景:他是将前端提交传递给后端的字符串日期时间转换为 Date 类型进行进行功能操作。
1、引入 Spring 及 SpringMVC 依赖,若不是 SpringBoot 或 SpringCloud 最好将下方 Spring 相关的依赖整合起来,避免项目时存在的问题;
如果是 SpringBoot、SpringCloud 在创建时都自动集成所以不用加。
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-oxm
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-test
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
2、如何使用 @DateTimeFormat 注解
(1) 在属性上加上 @DateTimeFormat 注解;
(2) 参数 pattern:需要转换的日期格式,当然也可以“yyyy-MM-dd HH:mm:ss”;
3、测试添加 @DateTimeFormat 注解效果,完美解决了参数传递类型转换问题。
如果不加 @DateTimeFormat 注解就报 400,参数类型无法传进接口,则不会响应:
三:这里还是聊下 Element-UI 的一个日期时间选择器差一天问题,之前在我整理的 @InitBinder 里面看过该功能的可以跳过,想了解 @InitBinder 进行日期转换的就点击该标题跳转去看下;
在前端日期选择器中添加:value-format=”yyyy-MM-dd”,也可以“yyyy-MM-dd HH:mm:ss”,就可以解决使用 Element-UI 日期时间选择器提交数据差一天的问题。
原文地址: Spring 家族之 @JsonFormat 与 @DateTimeFormat 注解进行日期时间格式及数据类型之间的转换 (SSM、SSMP、SpringBoot、SpringCloud)