SpringBoot统一时间处理

一、Date数据类型可以通过配置yml文件进行统一处理

  spring:
     jackson:
        date-format: yyyy-mm-dd
        time-zone: GMT+8

在这里插入图片描述

二、@Configuration 配置类 实现统一的时间处理 配合@JsonFormat 使用可灵活使用自定义时间格式

package com.sss.demo.ceshi;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @description:
 * @author: wd
 * @create: 2024-01-16 22:02
 **/
@Configuration
public class ReviewsConfig {


    private final static String pattern = "yyyy-MM-dd HH:mm:ss";


    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {

        return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

}

在这里插入图片描述

三、@JsonComponent

@JsonComponent注解用于将一个类标记为Spring MVC中的JSON序列化/反序列化组件。当你在Spring
MVC应用中使用@ResponseBody或@RequestBody注解时,Spring会使用Jackson库来进行JSON的序列化和反序列化。@JsonComponent注解可以用来标记一个类,使其成为一个自定义的JSON序列化/反序列化组件,也就是说,这个类可以定义如何将Java对象转换为JSON字符串,以及如何将JSON字符串转换为Java对象。

通过继承JsonSerializer <>实现对Date和LocalTimeDate进行重写,使用有一定的局限性,这里就不介绍了

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值