SpringBoot时间格式化

Date类型

java8推出了LocalDateTime 所以不太推荐使用Date了

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

LocalDateTime

1
2
3
4
5
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package com.shoukailiang.community.edu.config;

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;

/**
* @author shoukailiang
* @version 1.0
* @date 2021/8/6 16:53
*/
@Configuration
public class LocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format}")
private String pattern;

@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}

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

SpringBoot时间格式化
http://example.com/2021/08/13/SpringBoot时间格式化/
作者
shoukailiang
发布于
2021年8月13日
许可协议