SpringBoot三種方法接口返回日期格式化小結
方法一:@JsonFormat注解
在返回實體的字段上添加@JsonFormat注解。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createDate;
pattern是日期格式,timezone是時間分區(qū)。格式具體可以參考下圖:

方法二:JsonConfig配置
全局配置。好處:無需每個類配置日期格式壞處:不靈活,只能統(tǒng)一。
package com.xy.config;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
//jackson日期
@Slf4j
@JsonComponent
public class JacksonConfig {
@Value("${my.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
return builder -> {
TimeZone tz = TimeZone.getTimeZone("GMT+8");
DateFormat df = new SimpleDateFormat(pattern);
df.setTimeZone(tz);
builder.failOnEmptyBeans(false)
.failOnUnknownProperties(false)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.dateFormat(df);
};
}
@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}
然后配置文件里配置好格式就行。
方法三:yml配置
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
UTC和 GMT區(qū)別UTC:協調世界時間(UTC)是基于原子時鐘的時間計量系統(tǒng),旨在盡量接近世界時(UT)。UTC的時間尺度是均勻的,不考慮地球自轉速度的變化。GMT+8:格林威治平均時間加8小時,即東八區(qū)的本地時間。GMT+8通常用于表示中國北京時間UTC:在國際無線電通信、衛(wèi)星導航等需要高精度時間計量的場合廣泛使用。GMT+8:常用于表示中國北京時間,在電子郵件信頭、軟件顯示時間等場合使用??偨Y:UTC和GMT+8基本相同,UTC更精確而GMT+8常代表北京時間。
總結
三種方法個人推薦第三種。為什么,因為太方便了,另外如果有特殊格式,可以再加@JsonFormat單獨注解,會優(yōu)先以添加了@JsonFormat注解的為準。
到此這篇關于SpringBoot三種方法接口返回日期格式化小結的文章就介紹到這了,更多相關SpringBoot 接口返回日期格式化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解如何在Spring Boot啟動后執(zhí)行指定代碼
這篇文章主要介紹了在Spring Boot啟動后執(zhí)行指定代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
IntelliJ IDEA中properties文件顯示亂碼問題的解決辦法
今天小編就為大家分享一篇關于IntelliJ IDEA中properties文件顯示亂碼問題的解決辦法,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
Java實戰(zhàn)之小蜜蜂擴音器網上商城系統(tǒng)的實現
這篇文章主要介紹了如何利用Java實現簡單的小蜜蜂擴音器網上商城系統(tǒng),文中采用到的技術有JSP、Servlet?、JDBC、Ajax等,感興趣的可以動手試一試2022-03-03

