关于java:3种-Springboot-全局时间格式化方式别再写重复代码了

10次阅读

共计 4637 个字符,预计需要花费 12 分钟才能阅读完成。

本文收录在集体博客:www.chengxy-nds.top,技术材料共享,同提高

工夫格式化在我的项目中应用频率是十分高的,当咱们的 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.Datejava.util.Calendarjava.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 注解后,LocalDateTimeDate 工夫格式化胜利。

二、@JsonComponent 注解(举荐

这是我集体比拟举荐的一种形式,前边看到应用 @JsonFormat 注解并不能齐全做到全局工夫格式化,所以接下来咱们应用 @JsonComponent 注解自定义一个全局格式化类,别离对 DateLocalDate 类型做格式化解决。


@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());
    }
}

看到 DateLocalDate 两种工夫类型格式化胜利,此种形式无效。

但还有个问题,理论开发中如果我有个字段不想用全局格式化设置的工夫款式,想自定义格局怎么办?

那就须要和 @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 开发技巧,其实所谓的开发效率,不过是一个又一个开发技巧堆砌而来,聪慧的程序员总是能用起码的代码实现工作。

如果对你有用,欢送 在看 点赞 转发,您的认可是我最大的能源。

原创不易,焚烧秀发输入内容

习惯在 VX 看技术文章,想要获取更多 Java 资源的同学,能够关注我的公众号:程序员内点事,暗号:[666]

正文完
 0