• Springboot配置全局日期转换器


    1.Json传参方式

    package com.example.config;
    
    import java.text.FieldPosition;
    import java.text.ParsePosition;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.fasterxml.jackson.databind.util.StdDateFormat;
    import org.apache.commons.lang3.StringUtils;
    
    /**
     * JSON形式的全局时间类型转换器
     */
    public class CustomDateFormat extends StdDateFormat {
    
        private static final long serialVersionUID = -3201781773655300201L;
    
        public static final CustomDateFormat instance = new CustomDateFormat();
    
        @Override
        /**
         * 只要覆盖parse(String)这个方法即可
         */
        public Date parse(String dateStr, ParsePosition pos) {
            return getDate(dateStr, pos);
        }
    
        @Override
        public Date parse(String dateStr) {
            ParsePosition pos = new ParsePosition(0);
            return getDate(dateStr, pos);
        }
    
        private Date getDate(String dateStr, ParsePosition pos) {
            SimpleDateFormat sdf = null;
            if (StringUtils.isBlank(dateStr)) {
                return null;
            } else if (dateStr.matches("^\d{4}-\d{1,2}$")) {
                sdf = new SimpleDateFormat("yyyy-MM");
                return sdf.parse(dateStr, pos);
            } else if (dateStr.matches("^\d{4}-\d{1,2}-\d{1,2}$")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.parse(dateStr, pos);
            } else if (dateStr.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}$")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                return sdf.parse(dateStr, pos);
            } else if (dateStr.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}:\d{1,2}$")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return sdf.parse(dateStr, pos);
            } else if (dateStr.length() == 23) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                return sdf.parse(dateStr, pos);
            }
            return super.parse(dateStr, pos);
        }
    
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date, toAppendTo, fieldPosition);
        }
    
        @Override
        public CustomDateFormat clone() {
            return new CustomDateFormat();
        }
    }
    

    2.表单传参方式

    package com.example.config;
    
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.stereotype.Component;
    
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    /**
     * 表单形式的全局时间类型转换器
     */
    @Component
    public class DateConverter implements Converter<String, Date> {
    
        private static final List<String> formarts = new ArrayList<>(4);
    
        static {
            formarts.add("yyyy-MM");
            formarts.add("yyyy-MM-dd");
            formarts.add("yyyy-MM-dd HH:mm");
            formarts.add("yyyy-MM-dd HH:mm:ss");
        }
    
        @Override
        public Date convert(String source) {
            String value = source.trim();
            if ("".equals(value)) {
                return null;
            }
            if (source.matches("^\d{4}-\d{1,2}$")) {
                return parseDate(source, formarts.get(0));
            } else if (source.matches("^\d{4}-\d{1,2}-\d{1,2}$")) {
                return parseDate(source, formarts.get(1));
            } else if (source.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}$")) {
                return parseDate(source, formarts.get(2));
            } else if (source.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}:\d{1,2}$")) {
                return parseDate(source, formarts.get(3));
            } else {
                throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
            }
        }
    
        /**
         * 格式化日期
         *
         * @param dateStr String 字符型日期
         * @param format  String 格式
         * @return Date 日期
         */
        private Date parseDate(String dateStr, String format) {
            Date date = null;
            try {
                DateFormat dateFormat = new SimpleDateFormat(format);
                date = dateFormat.parse(dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return date;
        }
    
    }
    

    3.配置

    package com.example.config;
    
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.support.ConversionServiceFactoryBean;
    import org.springframework.core.convert.ConversionService;
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.http.MediaType;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.util.AntPathMatcher;
    import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        /**
         * 重写url路径匹配(忽略大小写敏感)
         */
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            antPathMatcher.setCaseSensitive(false);
        }
    
        /**
         * JSON全局日期转换器
         */
        @Bean
        public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
            MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
            //设置日期格式
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(CustomDateFormat.instance);
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
            //设置中文编码格式
            List<MediaType> list = new ArrayList<MediaType>();
            list.add(MediaType.APPLICATION_JSON_UTF8);
            mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
            return mappingJackson2HttpMessageConverter;
        }
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
            converters.add(getMappingJackson2HttpMessageConverter());
        }
    
        /**
         * 表单全局日期转换器
         */
        @Bean
        @Autowired
        public ConversionService getConversionService(DateConverter dateConverter){
            ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
            Set<Converter> converters = new HashSet<>();
            converters.add(dateConverter);
            factoryBean.setConverters(converters);
            return factoryBean.getObject();
        }
    }

      从此不再纠结用@DateTimeFormat(patten = "yyyyy-MM-dd")还是@DateTimeFormat(patten = "yyyyy-MM-dd HH:mm") ,告别烦恼,从全局时间转换器开始!!

      

  • 相关阅读:
    日期格式
    v-model修饰符
    从0到1构建全栈知识体系
    Element组件,v-for循环,表单验证方法
    上传文件转换为base64图片
    gulp4进阶
    gulp4快速入门
    TS-接口
    webpack4.0高级
    webpack4.0基础
  • 原文地址:https://www.cnblogs.com/joelan0927/p/11715062.html
Copyright © 2020-2023  润新知