在springboot中@RestController的返回会使用Jackson来将响应序列化为json格式,所以构建统一的响应中的日期格式可以定义统一的序列化参数来实现,springboot自带的时间格式定义怎么处理的
区别
@DateTimeFormat
@JsonFormat
使用方法
@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)
使用场景
URL传参时,格式化前端传向后端日期类型的时间格式
JSON传参,格式化前端传参和后端返回给前端的时间格式,传参可能不一定是json,但是一般接口向前端返回数据,基本上都是封装的统一返回格式,然后JSON返回。所以这个注解是一定要加的!
使用地方
实体类日期字段上、或者字段的set方法上、或者方法入参上
实体类日期字段上、或者字段的set方法上、、或者方法入参上
来源
org.springframework.format.annotation
com.fasterxml.jackson.annotation
注意:
一旦使用yyyy-MM-dd 格式,如果传时分秒就会报错,或者是使用 yyyy-MM-dd HH:mm:ss,如果传yyyy-MM-dd 也会报错。
假如是springboot项目的话,使用这两个注解是不用导其他的依赖包的!
框架当中默认他会认为 前端传的是UTC时间,然后SpringMVC在接到参数的时候,会进行转换为本地区时间,向前端返回参数的时候会转换为UTC时间!
这两个注解可以选择在实体类的set方法当中使用,也可以在字段上使用,效果是一样的!
2.在全局配置文件中设置 1 2 3 4 spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
3.通过JavaBean方式配置 定义DateForamtConfiguration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Configuration public class DateForamtConfiguration { public static final String timeFormat = "HH:mm:ss"; public static final String dateFormat = "yyyy-MM-dd"; public static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss"; /** * 全局时间格式化 */ @Bean public Jackson2ObjectMapperBuilderCustomizer customizer() { return builder -> { builder.simpleDateFormat(dateTimeFormat); //日期序列化 builder.serializers(new LocalTimeSerializer(DateTimeFormatter.ofPattern(timeFormat))); builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat))); builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat))); //日期反序列化 builder.deserializers(new LocalTimeDeserializer(DateTimeFormatter.ofPattern(timeFormat))); builder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormat))); builder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateTimeFormat))); }; } }