Springboot 全局时间格式化操作

时间格式化在项目中使用频率是非常高的,当我们的 API 接口返回结果,需要对其中某一个 date 字段属性进行特殊的格式化处理,通常会用到 SimpleDateFormat 工具处理。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime()));

可一旦处理的地方较多,不仅 CV 操作频繁,还产生很多重复臃肿的代码,而此时如果能将时间格式统一配置,就可以省下更多时间专注于业务开发了。

可能很多人觉得统一格式化时间很简单啊,像下边这样配置一下就行了,但事实上这种方式只对 date 类型生效。

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

而很多项目中用到的时间和日期API 比较混乱, java.util.Date 、 java.util.Calendar 和 java.time LocalDateTime 都存在,所以全局时间格式化必须要同时兼容性新旧 API。

看看配置全局时间格式化前,接口返回时间字段的格式。

@Data
public class OrderDTO {
    private LocalDateTime createTime;
    private Date updateTime;
}

很明显不符合页面上的显示要求(有人抬杠为啥不让前端解析时间,我只能说睡服代码比说服人容易得多~)

一、@JsonFormat 注解

@JsonFormat 注解方式严格意义上不能叫全局时间格式化,应该叫部分格式化,因为@JsonFormat 注解需要用在实体类的时间字段上,而只有使用相应的实体类,对应的字段才能进行格式化。

@Data
public class OrderDTO {
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private LocalDateTime createTime;
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

字段加上 @JsonFormat 注解后,LocalDateTime 和 Date 时间格式化成功。

二、@JsonComponent 注解(推荐)

这是我个人比较推荐的一种方式,前边看到使用 @JsonFormat 注解并不能完全做到全局时间格式化,所以接下来我们使用 @JsonComponent 注解自定义一个全局格式化类,分别对 Date 和 LocalDate 类型做格式化处理。

@JsonComponent
public class DateFormatConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * @author xiaofu
     * @description date 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

    /**
     * @author xiaofu
     * @description LocalDate 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

看到 Date 和 LocalDate 两种时间类型格式化成功,此种方式有效。

@JsonComponent 注解处理格式化

但还有个问题,实际开发中如果我有个字段不想用全局格式化设置的时间样式,想自定义格式怎么办?

那就需要和 @JsonFormat 注解配合使用了。

@Data
public class OrderDTO {
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private LocalDateTime createTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private Date updateTime;
}

从结果上我们看到 @JsonFormat 注解的优先级比较高,会以 @JsonFormat 注解的时间格式为主。

三、@Configuration 注解

这种全局配置的实现方式与上边的效果是一样的。

注意:在使用此种配置后,字段手动配置@JsonFormat 注解将不再生效。

@Configuration
public class DateFormatConfig2 {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;
    public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /**
     * @author xiaofu
     * @description Date 时间类型装换
     * @date 2020/9/1 17:25
     */
    @Component
    public class DateSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

    /**
     * @author xiaofu
     * @description Date 时间类型装换
     * @date 2020/9/1 17:25
     */
    @Component
    public class DateDeserializer extends JsonDeserializer<Date> {

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            try {
                return dateFormat.parse(jsonParser.getValueAsString());
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse date", e);
            }
        }
    }

    /**
     * @author xiaofu
     * @description LocalDate 时间类型装换
     * @date 2020/9/1 17:25
     */
    public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    /**
     * @author xiaofu
     * @description LocalDate 时间类型装换
     * @date 2020/9/1 17:25
     */
    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
        }
    }
}

SpringBoot全局日期格式转换失效问题记录

今天新搭建了一个项目, 像以前一样在一个配置类上做了个全局字符串转换日期对象的转换器!

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
           .............
        };
    }
}
//-----------------
//或者使用官网提供的 通过注解`@JsonComponent`来声明其静态内部类,都没生效!

但是发现失效了, 在debug模式下根本没有进来,没有任何反应! 后面发现原因在继承了WebMvcConfigurationSupport配置类,导致自动配置失效!

在网上找到的原因, 如下图所示:

自动配置在当WebMvcConfigurationSupport类不存在的时候才会生效WebMvc自动化配置,WebMvc自动配置类中不仅定义了classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/等路径的映射,还定义了配置文件spring.mvc开头的配置信息等。

类路径上的 HttpMessageConverter 失效

解决方案

是在自己继承了WebMvcConfigurationSupport上配置转换器:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport  {

    /**
     * 解决继承WebMvcConfigurationSupport,静态资源访问不到
     *
     * @param registry
     * @author: ZhiHao
     * @date: 2020/6/11
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
    /**
     * 解决继承WebMvcConfigurationSupport, json方式全局日期反序列化失效
     *
     * @param converters
     * @author: ZhiHao
     * @date: 2020/6/11
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                return DateConverterConfig.parse(jsonParser.getText());
            }
        });
        objectMapper.registerModule(module);
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }
    /**
     * 解决继承WebMvcConfigurationSupport, 普通请求,String转换Date-转换器
     *
     * @param registry
     * @author: ZhiHao
     * @date: 2020/6/11
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverterConfig());
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • springboot2.0 配置时间格式化不生效问题的解决

    在开发中日期最常打交道的东西之一,但是日期又会存在各式各样的格式,常见的情形就是,从数据库取出的日期往往都是时间戳(毫秒数)的形式,这个一般情况下是前端不想要的结果,需要进行处理,那在springboot中比较简单: pom.xml中添加依赖 <!-- 日期格式化 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter

  • 关于Springboot日期时间格式化处理方式总结

    项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式. 注:本文基于Springboot2.x测试,如果无法生效可能是spring版本较低导致的.PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam.PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数是使用ModelAttributeMethodProcessor进行处理,而

  • SpringBoot日期格式转换之配置全局日期格式转换器的实例详解

    1. SpringBoot设置后台向前台传递Date日期格式 在springboot应用中,@RestController注解的json默认序列化中,日期格式默认为:2020-12-03T15:12:26.000+00:00类型的显示. 在实际显示中,我们需要对其转换成我们需要的显示格式. 1.1 方式1:配置文件修改 配置文件配置application.yml: spring: # 配置日期格式化 jackson: date-format: yyyy-MM-dd HH:mm:ss #时间戳统一

  • springboot DTO字符字段与日期字段的转换问题

    不会自动转换string与date 主要是这个意思,前端提交的JSON里,日期是一个字符串,而对应后端的实体里,它是一个Date的日期,这两个在默认情况下是不能自动转换的,我们先看一下实体 实体 public class UserDTO { private String name; private String email; private Boolean sex; private Double total; private BigDecimal totalMoney; private Date

  • springboot全局日期格式化的两种方式

    方式一是配置参数 参数配置的方式就是在json序列化的时候,当字段为日期类型的时候的format类型,就相当于在所有日期字段上加了一个注解 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss"),但是每个字段都加注解太麻烦,所以直接使用全局配置来实现 参数配置也分为两种配置 第一种是yml的配置 spring: jackson: #参数意义: #JsonInclude.Include.A

  • Springboot 全局时间格式化操作

    时间格式化在项目中使用频率是非常高的,当我们的 API 接口返回结果,需要对其中某一个 date 字段属性进行特殊的格式化处理,通常会用到 SimpleDateFormat 工具处理. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime())); 可一旦处理的地方较多,不仅 CV

  • Springboot 全局日期格式化处理的实现

    最近部门几位同事受了一些委屈相继离职,共事三年临别之际颇有不舍,待一切手续办妥帖,寒暄过后送他们出公司,几个老哥临别时冲我鬼魅一笑,我顿时心里一紧有种不好的预感,这事绝对没有这么简单.等我接手这几个大佬的项目后,应验了我的预感,此刻我居然有点后悔,为啥送别之时没揍他们一顿!哈哈哈~ 而这种打人的冲动,在我开始优化几位老哥的项目时候,变得越来越强烈. 有个坑 技术部每个月都会组织一下代码走查及优化,以前是各自审查优化自己的项目,如今几位老哥的离职他们的项目就落到了我的头上.对于程序员来说最痛苦的事

  • SpringBoot中时间类型 序列化、反序列化、格式处理示例代码

    [SpringBoot] 中时间类型 序列化.反序列化.格式处理 Date yml全局配置 spring: jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss #配置POST请求Body中Date时间类型序列化格式处理,并返回 请求参数类型转换 /** * 时间Date转换 * 配置GET请求,Query查询Date时间类型参数转换 */ @Component public class DateConverter implemen

  • SpringBoot中时间格式化的五种方法汇总

    目录 前言 时间问题演示 1.前端时间格式化 JS 版时间格式化 2.SimpleDateFormat格式化 3.DateTimeFormatter格式化 4.全局时间格式化 实现原理分析 5.部分时间格式化 总结 参考 & 鸣谢 前言 在我们日常工作中,时间格式化是一件经常遇到的事儿,所以本文我们就来盘点一下 Spring Boot 中时间格式化的几种方法. 时间问题演示 为了方便演示,我写了一个简单 Spring Boot 项目,其中数据库中包含了一张 userinfo 表,它的组成结构和数

  • SpringBoot全局配置long转String丢失精度的问题解决

    目录 第一种方式 第二种方式 第三种方式 第四种方式(缺点:将所有的数字类型都会转为字符串) web项目中,Java后端传过来的Long/long类型,前端JS接收会丢失精度. 本文推荐第三.第四种方式 第一种方式 简单粗暴,将所有的Lang类型,改为String,数据库改成varchar类型: 第二种方式 自己建个配置类 extends WebMvcConfigurerAdapter 已经被弃用,直接实现WebMvcConfigurer该接口就行了 @EnableWebMvc @Configu

  • SpringBoot全局异常处理与定制404页面的方法

    一.错误处理原理分析 使用SpringBoot创建的web项目中,当我们请求的页面不存在(http状态码为404),或者器发生异常(http状态码一般为500)时,SpringBoot就会给我们返回错误信息. 也就是说,在SpringBoot的web项目中,会自动创建一个/error的错误接口,来返回错误信息.但是针对不同的访问方式,会有以下两种不同的返回信息.这主要取决于你访问时的http头部信息的Accept这个值来指定你可以接收的类型有哪些 使用浏览器访问时的头信息及其返回结果 Accep

  • Java日期时间格式化操作DateUtils 的整理

    Java日期时间格式化操作DateUtils 的整理 直接上代码,总结了开发过程中经常用到的日期时间格式化操作! import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; /** * ClassName: DateUtils <br/> * D

  • Java date format时间格式化操作示例

    本文实例讲述了Java date format时间格式化操作.分享给大家供大家参考,具体如下: import java.util.Date; import java.text.DateFormat; /** * 格式化时间类 * DateFormat.FULL = 0 * DateFormat.DEFAULT = 2 * DateFormat.LONG = 1 * DateFormat.MEDIUM = 2 * DateFormat.SHORT = 3 * @author Michael * @

  • springboot全局异常处理代码实例

    这篇文章主要介绍了springboot全局异常处理代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 前言: 开发中异常的处理必不可少,常用的就是 throw 和 try catch,这样一个项目到最后会出现很多冗余的代码,使用全局异常处理避免过多冗余代码. 全局异常处理: 1.pom 依赖(延续上一章代码): <dependencies> <!-- Spring Boot Web 依赖 --> <!-- Web 依赖

随机推荐