本文收錄在 GitHub 地址 https://github.com/chengxy-nds/Springboot-Notebookjavascript
時間格式化在項目中使用頻率是很是高的,當咱們的 API
接口返回結果,須要對其中某一個 date
字段屬性進行特殊的格式化處理,一般會用到 SimpleDateFormat
工具處理。前端
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime()));
可一旦處理的地方較多,不只 CV
操做頻繁,還產生不少重複臃腫的代碼,而此時若是能將時間格式統一配置,就能夠省下更多時間專一於業務開發了。java
可能不少人以爲統一格式化時間很簡單啊,像下邊這樣配置一下就好了,但事實上這種方式只對 date
類型生效。git
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
。程序員
看看配置全局時間格式化前,接口返回時間字段的格式。github
@Data public class OrderDTO { private LocalDateTime createTime; private Date updateTime; }
很明顯不符合頁面上的顯示要求(有人擡槓爲啥不讓前端解析時間,我只能說睡服代碼比說服人容易得多~)面試
1、@JsonFormat 註解
@JsonFormat
註解方式嚴格意義上不能叫全局時間格式化,應該叫部分格式化,由於@JsonFormat
註解須要用在實體類的時間字段上,而只有使用相應的實體類,對應的字段才能進行格式化。spring
@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
時間格式化成功。json
2、@JsonComponent 註解(推薦)
這是我我的比較推薦的一種方式,前邊看到使用 @JsonFormat
註解並不能徹底作到全局時間格式化,因此接下來咱們使用 @JsonComponent
註解自定義一個全局格式化類,分別對 Date
和 LocalDate
類型作格式化處理。app
@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
兩種時間類型格式化成功,此種方式有效。
但還有個問題,實際開發中若是我有個字段不想用全局格式化設置的時間樣式,想自定義格式怎麼辦?
那就須要和 @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; }
從結果上咱們看到 @JsonFormat
註解的優先級比較高,會以 @JsonFormat
註解的時間格式爲主。
3、@Configuration 註解
這種全局配置的實現方式與上邊的效果是同樣的。
注意:在使用此種配置後,字段手動配置
@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)); } } }
總結
分享了一個簡單卻又很實用的 Springboot
開發技巧,其實所謂的開發效率,不過是一個又一個開發技巧堆砌而來,聰明的程序員老是能用最少的代碼完成任務。
整理了幾百本各種技術電子書,送給小夥伴們。關注公號回覆【666】自行領取。和一些小夥伴們建了一個技術交流羣,一塊兒探討技術、分享技術資料,旨在共同窗習進步,若是感興趣就加入咱們吧!
不管你是剛入行、仍是已經有幾年經驗的程序員,相信這份面試提綱都會給你很多助力,長按二維碼關注 『 程序員內點事 』 ,回覆 『 offer 』 自行領取,祝你們 offer 拿到手軟