3种 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*/@Beanpublic 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*/@Beanpublic LocalDateTimeSerializer localDateTimeDeserializer() {return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));}@Beanpublic Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());}
}
看到 Date
和 LocalDate
两种时间类型格式化成功,此种方式有效。
但还有个问题,实际开发中如果我有个字段不想用全局格式化设置的时间样式,想自定义格式怎么办?
那就需要和 @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@Primarypublic 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*/@Componentpublic class DateSerializer extends JsonSerializer<Date> {@Overridepublic 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*/@Componentpublic class DateDeserializer extends JsonDeserializer<Date> {@Overridepublic 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> {@Overridepublic 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> {@Overridepublic LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));}}
}
总结
分享了一个简单却又很实用的 Springboot
开发技巧,其实所谓的开发效率,不过是一个又一个开发技巧堆砌而来,聪明的程序员总是能用最少的代码完成任务。
特别推荐一个分享架构+算法的优质内容,还没关注的小伙伴,可以长按关注一下:
长按订阅更多精彩▼如有收获,点个在看,诚挚感谢
3种 Springboot 全局时间格式化方式,别再写重复代码了相关推荐
- java date 格式化_3种 Springboot 全局时间格式化方式,别再写重复代码了
原文:3种 Springboot 全局时间格式化方式,别再写重复代码了 掘金 作者: 程序员内点事 时间格式化在项目中使用频率是非常高的,当我们的API接口返回结果,需要对其中某一个date字段属性进 ...
- Springboot实战:3种 Springboot 全局时间格式化方式
时间格式化在项目中使用频率是非常高的,当我们的 API 接口返回结果,需要对其中某一个 date 字段属性进行特殊的格式化处理,通常会用到 SimpleDateFormat 工具处理. SimpleD ...
- springboot 2.0 配置全局时间格式化
springboot 2.0 配置全局时间格式化 方式一: 在yml配置文件中添加以下配置 spring:jackson:date-format: yyyy-MM-dd HH:mm:sstime-zo ...
- Vue el-date-picker 组件时间格式化方式
Vue el-date-picker 组件时间格式化方式 1.使用el-date-picker组件 <el-form-item label="生日" :label-width ...
- 【hive】hive----自定义UDF 函数-----时间格式化以及取出双引号的代码
一.UDF的描述 用户自定义函数(UDF)是一个允许用户扩展HiveQL的强大的功能.用户可以使用Java编写自己的UDF,一旦将用户自定义函数加入到用户会话中(交互式的或者通过脚本执行的),它们就将 ...
- 奇淫巧技,springboot 全局日期格式化处理,有点香!
最近面了一些公司,有一些 Java方面的架构.面试资料,有需要的小伙伴可以在公众号[程序员内点事]里,无套路自行领取 说在前边 最近部门几位同事受了一些委屈相继离职,共事三年临别之际颇有不舍,待一切手 ...
- springboot 全局时间转换器
目录结构 前言 前端操作 Network Headers Network preview 后台日志信息 问题所在 解决办法一 解决办法二 参考链接 前言 前端框架:layui mini 后台框架:sp ...
- 字符串格式化成时间格式_JAVA | 常用的日期/时间格式化方式
引言 我们在开发过程中,在数据库中经常会看到beginTime.updateTime和endTime这些字段,这些可能是为了记录业务操作的某个时间.日期等信息.特此,总结一些在代码中常用的日期.时 ...
- SpringBoot时间格式化的5种方法!
作者 | 王磊 来源 | Java中文社群(ID:javacn666) 转载请联系授权(微信ID:GG_Stone) 在我们日常工作中,时间格式化是一件经常遇到的事儿,所以本文我们就来盘点一下 Spr ...
最新文章
- 图的最短路径dijkstra算法
- python实现直播服务非rtmp版本(非常简单)
- Nature:首个完全复现人眼的仿生眼问世,港科大造出半球形人工视网膜,感光性能超过人眼460倍...
- php 反序列化漏洞简介
- Linux 初始化之 Systemd机制
- 会计记忆总结之八:财务会计报告
- JVM内存管理概述与android内存泄露分析
- php msf dev product,3 框架运行环境
- 隐藏虚拟键盘,解决键盘挡住UITextField问题
- php smarty配置文件,Smarty配置文件
- 细说show slave status参数详解(最全)【转】
- 此文已删除,为何删不掉?
- python循环语句for 循环十次_Python 循环 while,for语句
- 软件项目管理复习题库(学生自制非官方)
- mfc服务器发送信息失败10057,基于MFC的局域网聊天工具.doc
- powerBI发布到web,管理员权限设置
- 7教程统计意义_极少人知道的SPSS数据拆分技巧——「杏花开生物医药统计」
- 重置linux红帽登录密码,红帽(RHEL)Linux 忘记root密码后重置密码
- 前端如何来做权限管理?
- linux nginx进程占用80端口杀不掉
热门文章
- linux下i2c设备驱动程序,Linux I2C 设备驱动
- python3连接mysql,python3连接MySQL数据库实例详解
- HDU1531(差分约束+Bellman_ford)
- HDU6141(最小树形图)
- E - Right-Left Cipher CodeForces - 1087A (模拟)
- Knative 入门系列1:knative 概述
- 【Unity 3D】学习笔记三十六:物理引擎——刚体
- 各个数据库取前10行记录
- AngularJs在IE10,11中的一个坑。
- JQuery Autocomplete实战