全局时间格式化

2023-12-25 18:02:16 浏览数 (2)

需求

经常会需要后端给前端传时间,有各种类型的时候,date、java8中LocalDateTime等等,虽然挺简单一个小事,但是也挺繁琐的,毕竟大家容易犯懒。

实践

代码(SpringBoot)

添加jackson依赖
代码语言:javascript复制
  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.2</version>
        </dependency>
修改application.properties
代码语言:javascript复制
######################################
#jackson.date-format
######################################
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT 8
时间格式化配置类
代码语言:javascript复制
package com.example.jsondemo;

import com.fasterxml.jackson.databind.SerializationFeature;
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.boot.jackson.JsonComponent;
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;

/**
 * @author CBeann
 * @create 2020-09-05 19:23
 */
@Configuration
@JsonComponent
public class DateFormatConfig {


    @Value("${spring.jackson.date-format}")
    private String pattern;

    /**
     * @description date 类型全局时间格式化
     * @date 2020-09-05 19:23
     */
    @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);
        };
    }

    /**
     * @description LocalDate 类型全局时间格式化
     * @date 2020-09-05 19:23
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}
实体类
代码语言:javascript复制
@Data
public class Student {

    private String name;
    private Date date;
    private LocalDateTime localDateTime;
    private LocalDate localDate;
    private LocalTime localTime;
}
测试
代码语言:javascript复制
@RequestMapping("/hello")
    public Object jsonObject() {
        Student student = new Student();
        student.setDate(new Date());
        student.setLocalDate(LocalDate.now());
        student.setLocalDateTime(LocalDateTime.now());
        student.setLocalTime(LocalTime.now());

        return student;
    }
测试结果

使用自定义格式

代码语言:javascript复制
@JsonFormat(locale = "zh", timezone = "GMT 8", pattern = "yyyy-MM-dd")
代码语言:javascript复制
@Data
public class Student {

    private String name;
    @JsonFormat(locale = "zh", timezone = "GMT 8", pattern = "yyyy-MM-dd")
    private Date date;
    @JsonFormat(locale = "zh", timezone = "GMT 8", pattern = "yyyy-MM-dd")
    private LocalDateTime localDateTime;
    private LocalDate localDate;
    private LocalTime localTime;
}

参考

3种 Springboot 全局时间格式化方式,别再写重复代码了

0 人点赞