Springboot 全局时间格式化

背景

Springboot 全局时间格式化,前后端日期类型参数格式化。

解决

方式大部分四种

1 @JsonFormat

字段加上 @JsonFormat 注解后,LocalDateTime 和 Date 时间格式化成功。需要在每个字段上添加该注解,不算全局时间格式化。不推荐

import com.fasterxml.jackson.annotation.JsonFormat;

@Data
public class TestDTO{
   

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

2 配置文件配置参数

这种方式只对 Date 类型生效。不推荐

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

3 @JsonComponent

自定义Configuration类。
Date、LocalDateTime类型日期均生效
推荐

/**
 * 全局日期格式化 如果某个字段不使用该格式
 * 依旧可以使用 @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd") 修改某个字段的格式化信息,且@JsonFormat优先级高于@JsonComponent配置的格式类型
 */
@JsonComponent
@Configuration
public class DateFormatConfig {
   

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

    /**
     * 类型全局时间格式化
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
   
        return builder -> {
   
            TimeZone tz = TimeZone.getTimeZone("GMT+8");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

    /**
     * 类型全局时间格式化
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
   
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
   
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

4 @Configuration

这种全局配置的实现方式与上边的效果是一样的。
注意:在使用此种配置后,字段手动配置@JsonFormat 注解将不再生效。
不推荐

@Configuration
public class DateFormatConfig2 {
   

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

    public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
   
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /**
     * 时间类型装换
     */
    @Component
    public class DateSerializer extends JsonSerializer<Date> {
   
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
   
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

    /**
     * 时间类型装换
     */
    @Component
    public class DateDeserializer extends JsonDeserializer<Date> {
   

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
   
            try {
   
                return dateFormat.parse(jsonParser.getValueAsString());
            } catch (ParseException e) {
   
                throw new RuntimeException("Could not parse date", e);
            }
        }
    }

    /**
     * 时间类型装换
     */
    public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
   
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
   
            gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    /**
     * 时间类型装换
     */
    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
   
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
   
            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
        }
    }
}

参考

  • https://developer.aliyun.com/article/771395

相关推荐

  1. Springboot 全局时间格式化

    2023-12-13 19:54:03       42 阅读
  2. spring boot 配置全局日期和时间格式

    2023-12-13 19:54:03       34 阅读
  3. SpringBoot 统一后端返回格式、处理全局异常

    2023-12-13 19:54:03       18 阅读
  4. 获取时间进行格式化

    2023-12-13 19:54:03       33 阅读
  5. Vue3 时间格式化

    2023-12-13 19:54:03       7 阅读
  6. SpringBoot全局异常捕获

    2023-12-13 19:54:03       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-13 19:54:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-13 19:54:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-13 19:54:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-13 19:54:03       18 阅读

热门阅读

  1. 车载ECU的发展趋势

    2023-12-13 19:54:03       37 阅读
  2. PyPDF2库对PDF实现读取的应用

    2023-12-13 19:54:03       41 阅读
  3. Android:FragmentHostCallback

    2023-12-13 19:54:03       44 阅读
  4. 挑战52天学小猪佩奇笔记--day19

    2023-12-13 19:54:03       39 阅读
  5. 低代码-传统开发者的噩梦?

    2023-12-13 19:54:03       29 阅读
  6. python版open3d给点云添加高斯噪声

    2023-12-13 19:54:03       32 阅读
  7. (5)快速搭建k8s集群

    2023-12-13 19:54:03       33 阅读