关于 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
相关推荐
神奇小汤圆6 分钟前
一条命令让你这辈子彻底解决"LF will be replaced by CRLF"(建议收藏)
后端
会编程的土豆7 分钟前
Go 里的 error 接口 + 假 nil(超级重点)
开发语言·后端·golang
涛声依旧-底层原理研究所7 分钟前
Node.js在高并发低延迟场景中的优势
java·人工智能·python·node.js
方也_arkling10 分钟前
【Java-Day09】继承
java·开发语言
西安邮电大学11 分钟前
Kafka保证消息顺序性
java·后端·kafka
迈巴赫车主11 分钟前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
xinhuanjieyi13 分钟前
JavaFX WebView 不支持 Brotli (br) 压缩编码警告修复
java
贺国亚16 分钟前
RAG 检索增强 · 向量库与 Chunking
后端·面试
Adair_z18 分钟前
[SEO艺术重读] 第13篇 SEO教育与研究
java·网络·数据库
晓杰'26 分钟前
从0到1实现Balatro游戏后端(5):得分计算与单局结算流程实现
后端·typescript·node.js·游戏开发·项目实战·nestjs·webscoket