美文网首页
spring boot 日期格式化

spring boot 日期格式化

作者: 渡人即渡己 | 来源:发表于2017-09-20 15:07 被阅读0次
    @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 不可用

    相关文章

      网友评论

          本文标题:spring boot 日期格式化

          本文链接:https://www.haomeiwen.com/subject/hbqjsxtx.html