关于LocalDateTime的全局返回时间带“T“的时间格式处理

本文介绍了在处理LocalDateTime时遇到的全局返回时间格式带有"T"的问题,分别探讨了使用Jackson和Fastjson时的解决方案,包括在Jackson中设置序列化配置以及在Fastjson中自定义SimpleDateFormatSerializer子类来避免日期转换异常。通过源码分析和实践测试,最终成功解决了时间格式化的问题。
摘要由CSDN通过智能技术生成

关于LocalDateTime的全局返回带"T"的时间格式处理

关于背景的大概描述,如下。
时间类型LocalDateTime相较于于Date的确有自己独特的优势,因此在之后的版本迭代上,将部分隔离开的模块使用了新型的LocalDateTime替代了Date,因已经使用了全局时间转换,但是测试的时候发现返回的时间格式很奇怪 2022-01-01T00:00:00.000,全局时间序列化、反序列化并没有起作用,寻找相关资料和DEGBU之后将相关资料整理如下。
目前常用的时间类型格式如下:

时间类型

时间默认格式

Date

Tue Feb 01 00:00:00 CST 2022

Timestamp

2022-01-01 00:00:00.0

LocalDateTime

2022-01-01T00:00:00.000

1.关于jackson的全局返回带T的处理方式

对于Date和Timestamp在引入LocalDateTime之前是经过spring.jackson.date-format进行全局数据绑定格式化时间类型。

spring:
	jackson:
		date-format: 格式化类

在格式化类中添加对LocalDateTime的格式化语句发现无效果。经过搜索资料后发现在使用jackson在对localDateTime类型的序列化和反序列化方法另有其他方法。(这里不输出关于源码内的信息。可自行查看。)

// 涉及源码类 其余的可自行debug追踪
Jackson2ObjectMapperBuilder
Jackson2ObjectMapperBuilderCustomizer // 最终做处理的服务类
JacksonAutoConfiguration


@Configuration
public class LocalDateTimeSerializerConfig {
	// jackson注册的时候会将序列化和反序列化的方法提前注册进,做数据转换会自行根据具体的实现去调用。
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot应用程序中使用MyBatis时,可以使用TypeHandler来解决LocalDateTime类型的全局配置时间转换问题。 首先,创建一个实现了TypeHandler接口的类,例如:LocalDateTimeTypeHandler。 ``` public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> { @Override public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException { if (parameter != null) { ps.setTimestamp(i, Timestamp.valueOf(parameter)); } else { ps.setNull(i, Types.TIMESTAMP); } } @Override public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException { Timestamp timestamp = rs.getTimestamp(columnName); return getLocalDateTime(timestamp); } @Override public LocalDateTime getResult(ResultSet rs, int columnIndex) throws SQLException { Timestamp timestamp = rs.getTimestamp(columnIndex); return getLocalDateTime(timestamp); } @Override public LocalDateTime getResult(CallableStatement cs, int columnIndex) throws SQLException { Timestamp timestamp = cs.getTimestamp(columnIndex); return getLocalDateTime(timestamp); } private LocalDateTime getLocalDateTime(Timestamp timestamp) { if (timestamp != null) { return timestamp.toLocalDateTime(); } return null; } } ``` 然后,在MyBatis的配置文件中将该TypeHandler注册为全局TypeHandler。 ``` <configuration> <typeHandlers> <typeHandler handler="com.example.LocalDateTimeTypeHandler"/> </typeHandlers> </configuration> ``` 这样,在使用LocalDateTime类型的时候,MyBatis就会自动调用该TypeHandler进行转换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值