版本
springboot3.1.1
mysql8
背景
springboot项目中使用localdatetime和localdate来表示时间和日期,mysql中设置datetime和date来接对应的类型。返回前端时,展示的格式为2020-02-02T02:02:02这样的格式,并不友好。但是前后端都有解决办法。
解决
1.新建配置类
2.复制粘贴
/**
* @Date: 2024/4/9
* @Version: v1.0.0
* @Description:
**/
@Configuration
public class LocalDateTimeConfig {
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
//日期转字符串
return builder -> builder.serializerByType(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER))
.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER))
.serializerByType(LocalTime.class, new LocalTimeSerializer(DatePattern.NORM_TIME_FORMATTER))
//字符串转日期
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DatePattern.NORM_TIME_FORMATTER));
}
}
end