springboot 日期转换器

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyDateConvert implements Converter {
    
    /**
     * 配置类型
     */
    private String [] pattern = {"yyyy-MM-dd","yyyy年MM月dd日"};
    @Override
    public Date convert(String s) {
        for (int i=0;i             try {
                return  new SimpleDateFormat(pattern[i]).parse(s);
            } catch (ParseException e) {
                continue;
            }
        }
        return null;
    }
}


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;

@Configuration
public class WebDateConfigurer extends WebMvcConfigurationSupport  {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @PostConstruct
    public void initEditableAvlidation() {

        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if(initializer.getConversionService()!=null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            genericConversionService.addConverter(new MyDateConvert());//添加自定义的类型转换器
        }
    }


}

你可能感兴趣的:(java问题集)