本文收录在个人博客: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 开发技巧,其实所谓的开发效率,不过是一个又一个开发技巧堆砌而来,聪明的程序员总是能用最少的代码完成任务。

如果对你有用,欢迎 在看点赞转发 ,您的认可是我最大的动力。

原创不易,燃烧秀发输出内容,如果有一丢丢收获,点个赞鼓励一下吧!

整理了几百本各类技术电子书,送给小伙伴们。关注公号回复【666】自行领取。和一些小伙伴们建了一个技术交流群,一起探讨技术、分享技术资料,旨在共同学习进步,如果感兴趣就加入我们吧!

3种 Springboot 全局时间格式化方式,别再写重复代码了的更多相关文章

  1. SpringBoot中时间格式化的5种方法!

    在我们日常工作中,时间格式化是一件经常遇到的事儿,所以本文我们就来盘点一下 Spring Boot 中时间格式化的几种方法. ​ 时间问题演示 为了方便演示,我写了一个简单 Spring Boot 项 ...

  2. SpringBoot全局时间转换器

    SpringBoot全局时间转换器 日常开发中,接收时间类型参数处处可见,但是针对不同的接口.往往需要的时间类型不一致 @DateTimeFormat(pattern = "yyyy-MM- ...

  3. VS开发中的代码编写小技巧——避免重复代码编写的几种方法

    上一篇文章中程序员的幸福生活--有你的日子,每天都是情人节,收到了大家的很多好评.鼓励和祝福,非常感动,真诚的谢谢大家.也希望每个朋友都能保持一个积极向上的心态,去迎接丰富多彩的人生. 在开发过程中, ...

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

    项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式. 注:本文基于Springboot2.x测试, ...

  5. 真没想到,Springboot能这样做全局日期格式化,有点香!

    最近面了一些公司,有一些 Java方面的架构.面试资料,有需要的小伙伴可以在公众号[程序员内点事]里,无套路自行领取 说在前边 最近部门几位同事受了一些委屈相继离职,共事三年临别之际颇有不舍,待一切手 ...

  6. js 中时间格式化的几种方法

    1.项目中时间返回值,很过时候为毫秒值,我们需要转换成 能够看懂的时间的格式: 例如: yyyy-MM-dd HH:mm:ss 2.处理方法(处理方法有多种,可以传值到前端处理,也可以后台可以好之后再 ...

  7. Go中的fmt几种输出的区别和格式化方式

    在日常使用fmt包的过程中,各种眼花缭乱的print是否让你莫名的不知所措呢,更让你茫然的是各种格式化的占位符..简直就是噩梦.今天就让我们来征服格式化输出,做一个会输出的Goer. fmt.Prin ...

  8. SpringBoot全局异常处理与定制404页面

    一.错误处理原理分析 使用SpringBoot创建的web项目中,当我们请求的页面不存在(http状态码为404),或者器发生异常(http状态码一般为500)时,SpringBoot就会给我们返回错 ...

  9. ie 与 Chrome 时间格式化问题.

    ie 与 Chrome 时间格式化通用: new Date(res[i].Time.replaceAll("-", "/")).format("yyy ...

随机推荐

  1. 2019 HL SC day10

    10天都过去了 4天都在全程懵逼.. 怎么可以这么难啊 我服了 现在想起依稀只记得一些结论 什么 反演? 什么后缀自动机?什么组合数的应用?什么神仙东西 ,不过讲课人的确都是神仙.(实名羡慕. mzx ...

  2. [转]Maven类包冲突终极三大解决技巧

    举例 A依赖于B及C,而B又依赖于X.Y,而C依赖于X.M,则A除引B及C的依赖包下,还会引入X,Y,M的依赖包(一般情况下了,Maven可通过<scope>等若干种方式控制传递依赖).这 ...

  3. requests入门实践01_下载2560*1080的电脑壁纸

    新版本移步:https://www.cnblogs.com/zy7y/p/13376228.html 附上代码 # !usr/bin/env python # -*- coding:utf-8 -*- ...

  4. ios数组基本用法和排序大全

    1.创建数组 // 创建一个空的数组 NSArray *array = [NSArray array]; // 创建有1个元素的数组 array = [NSArray arrayWithObject: ...

  5. 改变对象的字符串显示__str__repr

    改变对象的字符串显示 # l=list('hello') # # print(l) # file=open('test.txt','w') # print(file) class Foo: def _ ...

  6. stat 命令家族(1)- 详解 vmstat

    性能测试必备的 Linux 命令系列,可以看下面链接的文章哦 vmstat 介绍 Virtual Meomory Statistics,报告虚拟内存统计信息 会统计进程信息.内存.交换区.IO.磁盘. ...

  7. Python爬取网站上面的数据很简单,但是如何爬取APP上面的数据呢

  8. CSS变化、过渡与动画

    CSS变换用于在空间中移动物体,而CSS过渡和CSS关键帧动画用于控制元素随时间推移的变化. 变换.过渡和关键帧动画的规范仍然在制定中.尽管如此,其中大多数特性已经在常用浏览器中实现了. 1.二维变换 ...

  9. UIAutomator环境Android8.0 环境异常解决

    个人PC环境 ANDROID_HOME:F:\1Study\Andriod\51zxw_2018-0102\Sdk ANT_HOME:D:\ant\apache-ant-1.10.5\ CLASSPA ...

  10. 2020-06-27:ACID是什么?描述一下?

    福哥答案2020-06-27: 福哥口诀法:事原一隔持(事务属性ACID:原子性.一致性.隔离性.持久性) 用银行数据库来举例子解释一下这四个特性 原子性: 一个事务可能会包含多种操作,比如转账操作包 ...