关于 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
相关推荐
砚底藏山河17 分钟前
股票数据API接口:如何获取股票历历史分时KDJ数据
java·python·maven
Csvn24 分钟前
Python 性能优化与 Profiling 工具
后端·python
不减20斤不改头像1 小时前
手机一句话开发贪吃蛇!TRAE SOLO 移动端 AI 编程实测
前端·后端
明月_清风1 小时前
K8s 从入门到上手:核心概念+常用工具全解析
后端·kubernetes
随风,奔跑2 小时前
Nginx
服务器·后端·nginx·web
MegaDataFlowers2 小时前
运行若依项目
java
lulu12165440782 小时前
JetBrains IDE 终极AI编程方案:CC GUI插件让Claude Code和Codex丝滑运行
java·ide·人工智能·python·ai编程
('-')2 小时前
八股复习2:Java Array list和Linked list
java·开发语言
逸Y 仙X3 小时前
Elasticsearch时间类型实战
java·大数据·elasticsearch·搜索引擎·全文检索
Gerardisite3 小时前
企微批量群发消息指南:用 QiWe 省掉人工操作
java·python·机器人·企业微信