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

springboot接收日期字符串參數(shù)與返回日期字符串類型格式化

 更新時(shí)間:2024年01月20日 09:53:10   作者:jsq6681993  
這篇文章主要介紹了springboot接收日期字符串參數(shù)與返回日期字符串類型格式化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

接口請(qǐng)求接收日期字符串

方式一

全局注冊(cè)自定義Formatter

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new Formatter<Date>() {
            @Override
            public Date parse(String date, Locale locale) {
                return new Date(Long.parseLong(date));
            }

            @Override
            public String print(Date date, Locale locale) {
                return Long.valueOf(date.getTime()).toString();
            }
        });
    }
}

方式二

在接口參數(shù)使用@DateTimeFormat注解

// 在參數(shù)上加入該注解
@GetMapping("/testDate")
public void test(@DateTimeFormat(pattern = "yyyy-MM-dd")Date date){
}

方式三

參數(shù)映射實(shí)體類屬性上加@DateTimeFormat注解

@Data
public class User{
    private String name;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
}
// 在接收類字段加入該注解
@PostMapping("/testDate")
public void addUser(@RequestBody User user){
}

接口請(qǐng)求返回日期字符串格式化

方式一

全局注冊(cè)消息轉(zhuǎn)化器

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
     @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //調(diào)用父類的配置
        super.configureMessageConverters(converters);
        //創(chuàng)建fastJson消息轉(zhuǎn)換器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //創(chuàng)建配置類
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig .setDateFormat("yyyy-MM-dd HH:mm:ss");
        //保留空的字段
        fastJsonConfig .setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        // 按需配置,更多參考FastJson文檔
        fastConverter .setFastJsonConfig(config);
        fastConverter .setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(fastConverter );
    }
}

方式二

返回映射實(shí)體類屬性上加@JsonFormat注解

@Data
public class User{
    private String name;
    @JsonFormat(pattern="yyyy/MM/dd HH:mm:ss",timezone = "GMT+8")
    private Date birthday;
}

方式三

配置文件配置

spring:
    jackson:
        date-format: yyyy-MM-dd HH:mm:ss
        time-zone=GMT+8

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Idea工具中使用Mapper對(duì)象有紅線的解決方法

    Idea工具中使用Mapper對(duì)象有紅線的解決方法

    mapper對(duì)象在service層有紅線,項(xiàng)目可以正常使用,想知道為什么會(huì)出現(xiàn)這種情,接下來通過本文給大家介紹下Idea工具中使用Mapper對(duì)象有紅線的問題,需要的朋友可以參考下
    2022-09-09
  • 最新評(píng)論