欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot三種方法接口返回日期格式化小結(jié)

 更新時(shí)間:2025年01月10日 10:45:03   作者:weixin_46242847  
本文介紹了三種在Spring Boot中格式化接口返回日期的方法,包含使用@JsonFormat注解、全局配置JsonConfig、以及在yml文件中配置時(shí)區(qū),具有一定的參考價(jià)值,感興趣的可以了解一下

方法一:@JsonFormat注解

在返回實(shí)體的字段上添加@JsonFormat注解。

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;

pattern是日期格式,timezone是時(shí)間分區(qū)。格式具體可以參考下圖:

在這里插入圖片描述

方法二:JsonConfig配置

全局配置。好處:無(wú)需每個(gè)類配置日期格式壞處:不靈活,只能統(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‌:協(xié)調(diào)世界時(shí)間(UTC)是基于原子時(shí)鐘的時(shí)間計(jì)量系統(tǒng),旨在盡量接近世界時(shí)(UT)。UTC的時(shí)間尺度是均勻的,不考慮地球自轉(zhuǎn)速度的變化‌。‌GMT+8‌:格林威治平均時(shí)間加8小時(shí),即東八區(qū)的本地時(shí)間。GMT+8通常用于表示中國(guó)北京時(shí)間‌‌UTC‌:在國(guó)際無(wú)線電通信、衛(wèi)星導(dǎo)航等需要高精度時(shí)間計(jì)量的場(chǎng)合廣泛使用‌。‌GMT+8‌:常用于表示中國(guó)北京時(shí)間,在電子郵件信頭、軟件顯示時(shí)間等場(chǎng)合使用‌??偨Y(jié):UTC和GMT+8基本相同,UTC更精確而GMT+8常代表北京時(shí)間。

總結(jié)

三種方法個(gè)人推薦第三種。為什么,因?yàn)樘奖懔?,另外如果有特殊格式,可以再加@JsonFormat單獨(dú)注解,會(huì)優(yōu)先以添加了@JsonFormat注解的為準(zhǔn)。

到此這篇關(guān)于SpringBoot三種方法接口返回日期格式化小結(jié)的文章就介紹到這了,更多相關(guān)SpringBoot 接口返回日期格式化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論