本文转载请联系程序员内店师公众号。时间格式在项目中使用非常频繁。当我们的API接口返回结果时,我们需要对其中一个日期字段属性进行特殊的格式化处理,这通常由SimpleDateFormat工具进行处理。SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd");DatestationTime=dateFormat.parse(dateFormat.format(PayEndTime()));但是一旦处理的地方多了,不仅CV操作频繁,还会产生大量重复臃肿的代码。这时候如果能统一配置时间格式,就可以节省更多的时间来专注于业务发展。很多人可能觉得把时间统一格式化很简单,像下面这样配置就可以了,但实际上这种方法只对date类型生效。spring.jackson.date-format=yyyy-MM-ddHH:mm:ssspring.jackson.time-zone=GMT+8还有很多项目中使用的时间日期API比较混乱,java.util.Date,java.util都有.Calendar和java.timeLocalDateTime存在,因此全局时间格式必须与新旧API兼容。配置全局时间格式前请查看接口返回的时间字段格式。@DatapublicclassOrderDTO{privateLocalDateTimecreateTime;privateDateupdateTime;}显然不符合页面显示要求(为什么没有人大做文章让前端解析时间?我只能说睡代码比说服人容易多了~)没有做任何配置的结果、@JsonFormat注解@JsonFormat注解方法严格意义上不能称为全局时间格式化,应该称为部分格式化,因为@JsonFormat注解需要用在时间字段上实体类,只有使用对应的实体类时,对应的字段才能格式化。@DatapublicclassOrderDTO{@JsonFormat(locale="zh",timezone="GMT+8",pattern="yyyy-MM-dd")privateLocalDateTimecreateTime;@JsonFormat(locale="zh",timezone="GMT+8",pattern="yyyy-MM-ddHH:mm:ss")privateDateupdateTime;}为字段添加@JsonFormat注解后,LocalDateTime和Date时间格式化成功。@JsonFormat注解格式化2.@JsonComponent注解(推荐)这是我个人比较推荐的一种方式。看到使用@JsonFormat注解不能完全实现全局时间格式化,所以接下来我们使用@JsonComponent注解自动定义一个全局格式化类,分别对Date和LocalDate类型进行格式化。@JsonComponentpublicclassDateFormatConfig{@Value("${spring.jackson.date-format:yyyy-MM-ddHH:mm:ss}")privateStringpattern;/***@authorxiaofu*@descriptiondate类全局时间格式化*@date2020/8/3118:22*/@BeanpublicJackson2ObjectMapperBuilderCustomizerjackson2ObjectMapperBuilder(){returnbuilder->{TimeZonetz=TimeZone.getTimeZone("UTC");DateFormatdf=newSimpleDateFormat(pattern);df.setTimeZone(tz);builder.failOnEmptyBeans(false).failOnUnknownProperties(false)....ofPattern(pattern));}@BeanpublicJackson2ObjectMapperBuilderCustomizerjackson2ObjectMapperBuilderCustomizer(){returnbuilder->builder.serializerByType(LocalDateTime.class,localDateTimeDeserializer());}}看Date和LocalDate两种时间类型格式化成功。这个方法很有效。@JsonComponent注解处理了格式化,但是还是有问题。在实际开发中,如果我有一个字段不想使用全局格式设置的时间样式,想自定义格式怎么办?那么我需要和@JsonFormat注解一起使用。@DatapublicclassOrderDTO{@JsonFormat(locale="zh",timezone="GMT+8",pattern="yyyy-MM-dd")privateLocalDateTimecreateTime;@JsonFormat(locale="zh",timezone="GMT+8",pattern="yyyy-MM-dd")privateDateupdateTime;}从结果可以看出,@JsonFormat注解的优先级更高,@JsonFormat注解的时间格式会是主要的。3.@Configuration注解这个全局配置的实现和上面的效果是一样的。》注意:使用该配置后,字段手动配置的@JsonFormat注解将不再生效。”@ConfigurationpublicclassDateFormatConfig2{@Value("${spring.jackson.date-format:yyyy-MM-ddHH:mm:ss}")privateStringpattern;publicstaticDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");@Bean@PrimarypublicObjectMapperserializingObjectMapper(){ObjectMapperobjectMapper=newObjectMapper();JavaTimeModulejavaTimeModule=newJavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class,newLocalDateTimeSerializer());javaTimeModule.addDeserializer(LocalDateTime.class,newLocalDateTimeDeserializer());objectMapper.registerTimeModule;returnobjectMapper;}/***@authorxiaofu*@descriptionDate时间类型安装更换*@date2020/9/117:25*/@ComponentpublicclassDateSerializerextendsJsonSerializer
