SpringBoot 全局时间格式化【最新版本】(支持 Java 8+ 新时间类型,兼容旧类型)

一个配置,全局生效,再也不用一个一个属性加 @JsonSerialize@JsonSerialize 注解,或者更加暴力的手动 SimpleDateFormat 做时间转换了,从此给前端返时间变得如此简单。。。

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
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.time.format.DateTimeFormatter;

/**
 * @author xiandayang
 * @date 2019/7/11 15:55
 */
@Configuration
public class DateFormatConfiguration {

    private static final String dateFormat = "yyyy-MM-dd";

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

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // 定义传统时间类型的序列化格式:java.util.Date 
            jacksonObjectMapperBuilder.simpleDateFormat(dateTimeFormat);
            // 定义(Java 8+)时间类型序列化格式:LocalDate、LocalDateTime
            jacksonObjectMapperBuilder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
            jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
        };
    }
}

你可能感兴趣的:(工作记录)