1

你在写接口的时候难免会遇到接收String类型的日期参数(例如:2018-04-21 11:57:36)转换成Date类型情况。
百度了一番,发现大多数答案都是这样子的:

@Configuration
public class WebConfigBeans {

    @Autowired
    RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void initEditableValidation(){
       ConfigurableWebBindingInitializer configurableWebBindingInitializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if(configurableWebBindingInitializer.getConversionService()!=null){
            GenericConversionService service = (GenericConversionService) configurableWebBindingInitializer.getConversionService();
            service.addConverter(new StringToDateConverter());
        }
    }
}

上面的代码确实解决了问题,可是,代码有点不绿色节能。

以下是我的实现:
配置配置全局的String转Date参数转换器,可以简单解决这个问题!

web配置如下(spring boot 1.x 2.x 通用):

@Configuration
public class SpringMVCConfig extends WebMvcConfigurationSupport{

    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConverter());
    }
}

绿色环保更节能!

String转Date转换器实现如下(好吧,我承认下面的代码这是我抄来的):

public class StringToDateConverter implements Converter<String, Date> {

    
     private static final String dateFormat      = "yyyy-MM-dd HH:mm:ss";
     private static final String shortDateFormat = "yyyy-MM-dd";

        @Override
        public Date convert(String source) {
            if (StringUtils.isBlank(source)) {
                return null;
            }
            source = source.trim();
            try {
                if (source.contains("-")) {
                    SimpleDateFormat formatter;
                    if (source.contains(":")) {
                        formatter = new SimpleDateFormat(dateFormat);
                    } else {
                        formatter = new SimpleDateFormat(shortDateFormat);
                    }
                    return formatter.parse(source);
                } else if (source.matches("^\\d+$")) {
                    Long lDate = new Long(source);
                    return new Date(lDate);
                }
            } catch (Exception e) {
                throw new RuntimeException(String.format("parser %s to Date fail", source));
            }
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
}

one2three
7 声望0 粉丝

偶尔也写点东西,回馈社会吧