关于 SpringBoot 时间处理的总结

在我们的项目中处理时间可能会遇到这样的问题

下面是我在工作中的总结

DateTime、Date

java 复制代码
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

LocalDate、LocalDateTime

全局处理

Jackson处理

复制代码
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Configuration
public class LocalDateTimeConfiguration {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

            // 返回时间数据序列化
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));

            // 接收时间数据反序列化
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }
}

Fastjson处理

复制代码
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.DisableCircularReferenceDetect
        );
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(0, fastJsonHttpMessageConverter);
    }
}

单独处理

Jackson处理

复制代码
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime

Fastjson处理

java 复制代码
@JSONField(format= "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime
相关推荐
weixin_4414552612 分钟前
说说Java有哪些集合类
java·开发语言
码事漫谈16 分钟前
C++双向链表删除操作:由浅入深完全指南
后端
码事漫谈18 分钟前
软件生产的“高速公路网”:深入浅出理解CI/CD的核心流程
后端
合作小小程序员小小店18 分钟前
web网页开发,在线%台球俱乐部管理%系统,基于Idea,html,css,jQuery,jsp,java,ssm,mysql。
java·前端·jdk·intellij-idea·jquery·web
Moonbit1 小时前
MGPIC 初赛提交倒计时 4 天!
后端·算法·编程语言
程序定小飞1 小时前
基于springboot的作业管理系统设计与实现
java·开发语言·spring boot·后端·spring
晓庆的故事簿1 小时前
windows下载和使用minio,结合java和vue上传文件
java·开发语言
程序员小假1 小时前
我们来说一下 Mybatis 的缓存机制
java·后端
qq_336313931 小时前
java基础-学生管理系统升级
java
沙虫一号1 小时前
线上python问题排查思路
后端·python