spring boot 日期格式化

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

方式一(配置文件方式):注意: 使用配置文件方式的话,不能存在带@EnableWebMvc注解的配置类,否则其作用会被屏蔽!!!

1、如果是application.yml配置文件,在文件中加入如下配置

spring: 
  jackson: 
    date-format: yyyy-MM-dd HH:mm:ss  

方式二(配置类方式):创建配置类WebConfig.java,注意不能缺少@EnableWebMvc和@Configuration注解以及代码中两个方法所引用的类要正确。

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 定义时间格式转换器
 */
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    //定义时间格式转换器

    @Bean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(mapper);
        return converter;
    }//添加转换器@Override

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        //将我们定义的时间格式转换器添加到转换器列表中, 
        // 这样jackson格式化时候但凡遇到Date类型就会转换成我们定义的格式 
        converters.add(jackson2HttpMessageConverter());
    }
}

如果上面两种方式配置同时存在,只有第二种会起作用。

注意第二中方法 会过滤掉 你的html 页面 导致 swagger-ui 不可用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容