springMVC 配置自定义日期转换器

写一个类


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

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

public class DateConverter implements Converter<String,Date> {

     @Override
        public Date convert(String source) {
         SimpleDateFormat sdf = getDateFormat(source);
            try {
                return sdf.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }
     /**
         * 获取传入字符串所属的日期格式
         * 
         * @param source
         * @return
         */
        private SimpleDateFormat getDateFormat(String source) {
            SimpleDateFormat sdf = new SimpleDateFormat();
            //添加想要使用的日期类格式,即可达到多种日期格式
            if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) {
                sdf = new SimpleDateFormat("yyyy/MM/dd");
            } else if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) {
                sdf = new SimpleDateFormat("yyyyMMdd");
            }
            return sdf;
        }
}

xml配置

  <!-- 配置注解驱动 -->
    <mvc:annotation-driven conversion-service="conversionService" />
    
    
     <!--配置自定义日期转换器-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.ljw.springmvc.converter.DateConverter"></bean>
            </list>
        </property>
    </bean>

发布了4 篇原创文章 · 获赞 0 · 访问量 22

猜你喜欢

转载自blog.csdn.net/luojiawen208/article/details/104971558