SpringBoot全局日期格式配置的方法總結(jié)
spring boot中,不想每個(gè)實(shí)體類中都這樣設(shè)置,有什么方法:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;在Spring Boot中有幾種方法可以避免在每個(gè)實(shí)體類中重復(fù)設(shè)置@JsonFormat注解:
方法一:全局配置(推薦)
在application.yml或application.properties中配置全局的日期格式:
YAML配置:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
write-dates-as-timestamps: falseProperties配置:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.write-dates-as-timestamps=false
方法二:自定義Jackson配置類
@Configuration
public class JacksonConfig {
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return builder -> {
// 設(shè)置全局日期格式
builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.timeZone(TimeZone.getTimeZone("GMT+8"));
// 針對(duì)Java 8時(shí)間API的配置
builder.serializers(new LocalDateTimeSerializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.deserializers(new LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// 如果需要,也可以配置LocalDate等其他類型
builder.serializers(new LocalDateSerializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd")));
builder.deserializers(new LocalDateDeserializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd")));
};
}
}方法三:更詳細(xì)的配置類
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 設(shè)置Java 8時(shí)間模塊
JavaTimeModule javaTimeModule = new JavaTimeModule();
// LocalDateTime序列化和反序列化
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// LocalDate序列化和反序列化
javaTimeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return objectMapper;
}
}方法四:使用Mixin(為特定類型統(tǒng)一配置)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
abstract class LocalDateTimeMixin {
}
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomSerialization() {
return builder -> {
builder.mixIn(LocalDateTime.class, LocalDateTimeMixin.class);
};
}
}方法五:自定義注解(如果需要不同格式)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public @interface DefaultDateTimeFormat {
}
// 使用方式
@DefaultDateTimeFormat
private LocalDateTime createTime;推薦方案
建議使用方法一(全局配置),最簡(jiǎn)單直接,能滿足大部分場(chǎng)景。
如果項(xiàng)目中有多種不同的日期格式需求,可以:
- 使用方法一設(shè)置默認(rèn)格式
- 對(duì)于特殊格式的字段,使用
@JsonFormat覆蓋全局配置
// 全局使用 yyyy-MM-dd HH:mm:ss // 特殊字段使用其他格式 @JsonFormat(pattern = "yyyy/MM/dd") private LocalDate specialDate;
這樣既能減少重復(fù)代碼,又能保持靈活性。
已經(jīng)設(shè)置日期格式:
jackson:
# 全局配置日期格式,這樣就不用每個(gè)實(shí)體類的日期屬性使用 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
write-dates-as-timestamps: false
deserialization:
adjust-dates-to-context-time-zone: false
package com.weiyu.model;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 打印模板列表 VO
*/
@Data
public class PrintTemplateListVO {
private Integer id;
private String templateType;
private String templateName;
private String templateCode;
private String printDirection;
private Boolean enabled;
private String createBy;
private LocalDateTime createTime;
private String updateBy;
private LocalDateTime updateTime;
}
但是為什么前端顯示的日期內(nèi)容是:2025-12-19T16:17:32.717這是因?yàn)槿峙渲玫?nbsp;date-format 只對(duì) java.util.Date 類型有效,對(duì)于 Java 8 的 LocalDateTime 類型不生效。需要單獨(dú)配置 Java 8 時(shí)間模塊。
解決方案:
方案一:創(chuàng)建 Jackson 配置類(推薦)
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfig {
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new Jackson2ObjectMapperBuilder()
.modulesToInstall(new JavaTimeModule())
.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.simpleDateFormat(DATE_TIME_FORMAT)
.timeZone(java.util.TimeZone.getTimeZone("GMT+8"));
}
}方案二:更完整的配置類
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
@Configuration
public class JacksonConfig {
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return builder -> {
// 配置 Java 8 時(shí)間模塊
builder.modulesToInstall(new JavaTimeModule());
// 配置 LocalDateTime 的序列化和反序列化
builder.serializers(new LocalDateTimeSerializer(
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
builder.deserializers(new LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
// 其他配置
builder.simpleDateFormat(DATE_TIME_FORMAT);
builder.timeZone(TimeZone.getTimeZone("GMT+8"));
builder.featuresToDisable(
com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
);
};
}
}方案三:完整的 ObjectMapper Bean
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 配置 LocalDateTime
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
mapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setTimeZone(java.util.TimeZone.getTimeZone("GMT+8"));
return mapper;
}
}方案四:添加依賴(如果未添加)
確保你的 pom.xml 中包含 Jackson Java 8 時(shí)間模塊的依賴:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>驗(yàn)證配置
添加配置后,LocalDateTime 字段應(yīng)該會(huì)正確格式化為 "2025-12-19 16:17:32",而不是 "2025-12-19T16:17:32.717"。
為什么需要單獨(dú)配置?
date-format: yyyy-MM-dd HH:mm:ss只適用于傳統(tǒng)的java.util.DateLocalDateTime是 Java 8 引入的新 API,需要額外的 Jackson 模塊支持- Spring Boot 默認(rèn)會(huì)注冊(cè)
JavaTimeModule,但沒(méi)有應(yīng)用自定義格式
建議使用方案一,它比較簡(jiǎn)潔且能解決問(wèn)題。配置后不需要在每個(gè)實(shí)體類中添加 @JsonFormat 注解。
代碼實(shí)例:
package com.weiyu.config;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.format.DateTimeFormatter;
/**
* Jackson JSON 序列化/反序列化全局配置類
* <p>
* 作用:統(tǒng)一配置項(xiàng)目中日期時(shí)間類型的 JSON 格式化方式
* 解決:LocalDateTime 等 Java 8 時(shí)間類型在前端顯示為 ISO 格式(如:2025-12-19T16:17:32.717)的問(wèn)題
* 效果:所有 LocalDateTime 字段將統(tǒng)一格式化為 "yyyy-MM-dd HH:mm:ss"
* <p>
* 配置效果總結(jié):
* 1. 序列化(對(duì)象 → JSON):
* - LocalDateTime: 格式化為 "yyyy-MM-dd HH:mm:ss"
* - java.util.Date: 格式化為 "yyyy-MM-dd HH:mm:ss"
* - 其他 Java 8 時(shí)間類型(LocalDate、LocalTime):使用默認(rèn)格式
* <p>
* 2. 反序列化(JSON → 對(duì)象):
* - 能正確解析 "yyyy-MM-dd HH:mm:ss" 格式的字符串為 LocalDateTime
* - 也支持其他常見(jiàn)日期格式
* <p>
* 3. 優(yōu)勢(shì):
* - 無(wú)需在每個(gè)實(shí)體類的字段上添加 @JsonFormat 注解
* - 統(tǒng)一整個(gè)項(xiàng)目的日期時(shí)間格式
* - 同時(shí)支持新舊日期 API(java.util.Date 和 java.time)
* <p>
* 4. 注意事項(xiàng):
* - 如果某個(gè)字段需要特殊格式,仍可使用 @JsonFormat 覆蓋此全局配置
* - 此配置不會(huì)影響數(shù)據(jù)庫(kù)存儲(chǔ),僅影響 JSON 序列化/反序列化
*/
@Configuration // 聲明這是一個(gè) Spring 配置類,Spring 啟動(dòng)時(shí)會(huì)自動(dòng)掃描并加載
public class JacksonConfig {
/**
* 從 application.yml 中讀取日期格式配置
* 使用默認(rèn)值:如果配置文件中沒(méi)有 spring.jackson.date-format,則使用 "yyyy-MM-dd HH:mm:ss"
*/
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String dateFormat;
/**
* 從 application.yml 中讀取時(shí)區(qū)配置
* 使用默認(rèn)值:如果配置文件中沒(méi)有 spring.jackson.time-zone,則使用 "Asia/Shanghai"
*/
@Value("${spring.jackson.time-zone:Asia/Shanghai}")
private String timeZone;
/**
* 創(chuàng)建并配置 Jackson2ObjectMapperBuilder Bean
* <p>
* 這個(gè)方法返回的 Jackson2ObjectMapperBuilder 會(huì)被 Spring 用于創(chuàng)建所有 ObjectMapper 實(shí)例
* 包括 REST Controller 返回 JSON 時(shí)使用的 ObjectMapper
*
* @return 配置好的 Jackson2ObjectMapperBuilder 實(shí)例
*/
@Bean // 聲明這是一個(gè) Spring Bean,Spring 容器會(huì)管理它的生命周期
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
// 使用 Builder 模式鏈?zhǔn)脚渲?Jackson
return new Jackson2ObjectMapperBuilder()
// 1. 安裝 JavaTimeModule 模塊
// 作用:讓 Jackson 支持 Java 8 的時(shí)間類型(LocalDateTime、LocalDate、LocalTime等)
// 如果沒(méi)有這個(gè)模塊,Jackson 無(wú)法正確處理 Java 8 時(shí)間類型
.modulesToInstall(new JavaTimeModule())
// 2. 配置序列化器
// 作用:將 LocalDateTime、LocalDate、LocalTime 對(duì)象轉(zhuǎn)換為 JSON 字符串時(shí)使用的格式化規(guī)則
// 示例:LocalDateTime.now() → "2025-12-19 16:17:32"
.serializers(
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat)),
new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))
)
// 3. 配置反序列化器
// 作用:將 JSON 字符串轉(zhuǎn)換為 LocalDateTime 對(duì)象時(shí)使用的解析規(guī)則
// 示例:"2025-12-19 16:17:32" → LocalDateTime、LocalDate、LocalTime 對(duì)象
.deserializers(
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateFormat)),
new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss"))
)
// 4. 配置傳統(tǒng) java.util.Date 類型的日期格式
// 作用:傳統(tǒng) Date 類型也使用相同的日期格式
// 兼容性:確保項(xiàng)目中既有 java.util.Date 也有 java.time 類型時(shí),格式保持一致
.simpleDateFormat(dateFormat)
// 5. 配置時(shí)區(qū)
// 作用:設(shè)置序列化和反序列化時(shí)的默認(rèn)時(shí)區(qū)
// 重要:時(shí)區(qū)設(shè)置會(huì)影響日期時(shí)間的顯示和解析
// "Asia/Shanghai" - 中國(guó)標(biāo)準(zhǔn)時(shí)間(UTC+8)
// 注意:LocalDateTime 不包含時(shí)區(qū)信息,此設(shè)置主要影響 Date 和 Instant 類型
.timeZone(java.util.TimeZone.getTimeZone(timeZone));
}
}以上就是SpringBoot全局日期格式配置的方法總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot全局日期格式配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳談spring中bean注入無(wú)效和new創(chuàng)建對(duì)象的區(qū)別
這篇文章主要介紹了spring中bean注入無(wú)效和new創(chuàng)建對(duì)象的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java持久化框架Hibernate與Mybatis優(yōu)劣及選擇詳解
這篇文章主要介紹了Java持久化框架Hibernate與Mybatis優(yōu)劣及選擇詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
Jenkins打包Maven項(xiàng)目找不到mvn:not found的解決方案
文章講述了在使用Docker重新部署Jenkins并使用流水線腳本打包項(xiàng)目時(shí)遇到的編譯找不到mvn命令的問(wèn)題,通過(guò)檢查Jenkins服務(wù)器上的Maven安裝、Maven插件、全局工具配置以及系統(tǒng)環(huán)境變量,最終解決了問(wèn)題2025-11-11
Java ArrayList集合詳解(Java動(dòng)態(tài)數(shù)組)
這篇文章主要介紹了Java ArrayList集合詳解(Java動(dòng)態(tài)數(shù)組),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
java7 簡(jiǎn)化變參方法調(diào)用實(shí)例方法
在本篇文章里我們給大家整理的是關(guān)于java7 簡(jiǎn)化變參方法調(diào)用實(shí)例方法以及實(shí)例代碼,需要的朋友們學(xué)習(xí)下。2019-11-11

