Springboot 全局時間格式化三種方式示例詳解
時間格式化在項目中使用頻率是非常高的,當(dāng)我們的 API? 接口返回結(jié)果,需要對其中某一個 date? 字段屬性進(jìn)行特殊的格式化處理,通常會用到 SimpleDateFormat? 工具處理。
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime()));可一旦處理的地方較多,不僅 CV? 操作頻繁,還產(chǎn)生很多重復(fù)臃腫的代碼,而此時如果能將時間格式統(tǒng)一配置,就可以省下更多時間專注于業(yè)務(wù)開發(fā)了。
可能很多人覺得統(tǒng)一格式化時間很簡單啊,像下邊這樣配置一下就行了,但事實上這種方式只對 date? 類型生效。
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8
而很多項目中用到的時間和日期API? 比較混亂, java.util.Date? 、 java.util.Calendar? 和 java.time LocalDateTime? 都存在,所以全局時間格式化必須要同時兼容性新舊 API?。
看看配置全局時間格式化前,接口返回時間字段的格式。
@Data
public class OrderDTO {
private LocalDateTime createTime;
private Date updateTime;
}很明顯不符合頁面上的顯示要求(有人抬杠為啥不讓前端解析時間,我只能說睡服代碼比說服人容易得多~ )

?一、@JsonFormat 注解
?@JsonFormat? 注解方式嚴(yán)格意義上不能叫全局時間格式化,應(yīng)該叫部分格式化,因為@JsonFormat? 注解需要用在實體類的時間字段上,而只有使用相應(yīng)的實體類,對應(yīng)的字段才能進(jìn)行格式化。
@Data
public class OrderDTO {
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
private LocalDateTime createTime;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}字段加上 @JsonFormat? 注解后,LocalDateTime? 和 Date? 時間格式化成功。

?二、@JsonComponent 注解(推薦)
這是我個人比較推薦的一種方式,前邊看到使用 @JsonFormat? 注解并不能完全做到全局時間格式化,所以接下來我們使用 @JsonComponent? 注解自定義一個全局格式化類,分別對 Date? 和 LocalDate? 類型做格式化處理。
@JsonComponent
public class DateFormatConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
/**
* @author xiaofu
* @description date 類型全局時間格式化
* @date 2020/8/31 18:22
*/
@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);
};
}
/**
* @author xiaofu
* @description LocalDate 類型全局時間格式化
* @date 2020/8/31 18:22
*/
@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}看到 Date? 和 LocalDate? 兩種時間類型格式化成功,此種方式有效。

但還有個問題,實際開發(fā)中如果我有個字段不想用全局格式化設(shè)置的時間樣式,想自定義格式怎么辦?
那就需要和 @JsonFormat? 注解配合使用了。
@Data
public class OrderDTO {
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
private LocalDateTime createTime;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
private Date updateTime;
}從結(jié)果上我們看到 @JsonFormat? 注解的優(yōu)先級比較高,會以 @JsonFormat? 注解的時間格式為主。

?三、@Configuration 注解
這種全局配置的實現(xiàn)方式與上邊的效果是一樣的。
注意:在使用此種配置后,字段手動配置@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;
}
/**
* @author xiaofu
* @description Date 時間類型裝換
* @date 2020/9/1 17:25
*/
@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);
}
}
/**
* @author xiaofu
* @description Date 時間類型裝換
* @date 2020/9/1 17:25
*/
@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);
}
}
}
/**
* @author xiaofu
* @description LocalDate 時間類型裝換
* @date 2020/9/1 17:25
*/
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)));
}
}
/**
* @author xiaofu
* @description LocalDate 時間類型裝換
* @date 2020/9/1 17:25
*/
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
}
}
}
?總結(jié)
分享了一個簡單卻又很實用的 Springboot? 開發(fā)技巧,其實所謂的開發(fā)效率,不過是一個又一個開發(fā)技巧堆砌而來,聰明的程序員總是能用最少的代碼完成任務(wù)。
到此這篇關(guān)于3 種 Springboot 全局時間格式化方式的文章就介紹到這了,更多相關(guān)Springboot 全局時間格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java與Node.js利用AES加密解密出相同結(jié)果的方法示例
這篇文章主要介紹了Java與Node.js利用AES加密解密出相同結(jié)果的方法,文中給出了詳細(xì)的示例代碼,相信對大家的學(xué)習(xí)或者工作能帶來一定的幫助,需要的朋友們下面來一起看看吧。2017-02-02
詳細(xì)講解springboot如何實現(xiàn)異步任務(wù)
異步:異步與同步相對,當(dāng)一個異步過程調(diào)用發(fā)出后,調(diào)用者在沒有得到結(jié)果之前,就可以繼續(xù)執(zhí)行后續(xù)操作。也就是說無論異步方法執(zhí)行代碼需要多長時間,跟主線程沒有任何影響,主線程可以繼續(xù)向下執(zhí)行2022-04-04
Java實現(xiàn)調(diào)用ElasticSearch?API的示例詳解
這篇文章主要為大家詳細(xì)介紹了Java調(diào)用ElasticSearch?API的效果資料,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的可以了解一下2023-03-03
java調(diào)用webService接口的代碼實現(xiàn)
本文主要介紹了java調(diào)用webService接口的代碼實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
springboot實現(xiàn)發(fā)送郵件(QQ郵箱為例)
這篇文章主要為大家詳細(xì)介紹了springboot實現(xiàn)發(fā)送郵件,qq郵箱代碼實現(xiàn)郵件發(fā)送,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06
Java內(nèi)存模型之happens-before概念詳解
happens-before原則非常重要,它是判斷數(shù)據(jù)是否存在競爭、線程是否安全的主要依據(jù),依靠這個原則,我們解決在并發(fā)環(huán)境下兩操作之間是否可能存在沖突的所有問題。下面我們就一個簡單的例子稍微了解下happens-before知識,感興趣的朋友一起看看吧2021-06-06

