您的位置 首页 java

统一处理返回前端日期格式化去T,返回前端损失精度问题

一、前言

我们在实际开发中肯定会遇到后端的时间传到前端是这个样子的: 2022-08-02T15:43:50
这个时候前后端就开始踢皮球了,!!
后端说:前端来做就可!
前端说:后端来做就可!
作为一名有责任感的后端,这种事情怎么能让前端来搞呢!
还有就是 Long 类型的返回到前端可能会损失精度,这个情况只能后端来做了!

解决方案还是看的开源框架,人家写的,咱就不造轮子了!直接开车!!

二、错误示范

带着 T 非常不好,产品要求不带,哈哈,一切按照原型来哦!!

下面的 testNum 的值是Long类型的最大值: 9223372036854775807 ,这样就会损失精度成: 9223372036854776000

三、导入依赖

 <!-- json 模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
  

四、编写配置类

 @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfiguration {

@Bean
@ConditionalOnMissingBean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
// 设置日期格式
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
// 解决long类型损失精度
builder.serializerByType(Long.class, ToStringSerializer.instance);
// 日期格式自定义类
builder.modules(new PigJavaTimeModule());
};
}

}
  
 public class  Java TimeModule  extends  SimpleModule {

public JavaTimeModule() {
super(PackageVersion.VERSION);

// ======================= 时间序列化规则 ===============================
// yyyy-MM-dd HH:mm:ss
this.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
// yyyy-MM-dd
this.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
// HH:mm:ss
this.addSerializer(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));

// Instant 类型序列化
this.addSerializer(Instant.class, InstantSerializer.INSTANCE);

// ======================= 时间反序列化规则 ==============================
// yyyy-MM-dd HH:mm:ss
this.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
// yyyy-MM-dd
this.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
// HH:mm:ss
this.addDeserializer(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
// Instant 反序列化
this.addDeserializer(Instant.class, InstantDeserializer.INSTANT);
}

}

  

五、测试成果

我们发现日期的烦人的 T 被去掉了!再也不用踢皮球了哦!!

我们发现后端返回的类型为 Long 时,会自动变为 String 类型,再也不会损失精度了,这个很容易忽视!!

如果觉得有用,一键三连起来,小编谢谢大家了!!

文章来自

文章来源:智云一二三科技

文章标题:统一处理返回前端日期格式化去T,返回前端损失精度问题

文章地址:https://www.zhihuclub.com/181599.shtml

关于作者: 智云科技

热门文章

网站地图