SpringMVC写一个时间格式转换器(DateConverter)

可借鉴网站:https://blog.csdn.net/achuo/article/details/50606254

在工具包里写一个时间格式转换类:

package com.neuedu.crm.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.springframework.core.convert.converter.Converter;

/**
 * 日期格式转换算法
 * @author mechan
 */
public class DateConverter implements Converter<String, Date> {	
	
	@Override
	public Date convert(String source ) {
		//编写时间转换器,支持多种时间格式
		SimpleDateFormat sdf = getSimpleDateFormat(source);
		try {
			Date date = sdf.parse(source);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	private SimpleDateFormat getSimpleDateFormat( String source ) {
		SimpleDateFormat sdf = new SimpleDateFormat();
		if( Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source )) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		} else {
			System.out.println("日期格式错误");
		}
		return sdf;
	}
}

原理:(如果有伙伴想知道converter 的实现原理,可以百度,DateConverter是实现了Converter接口,重写了convert()方法实现的)

然后把这个时间格式转换工具类的全类名,配置在SpringMVC的配置文件中

    <!-- 注册转化器与验证器 -->
    <mvc:annotation-driven conversion-service="conversion-service" validator="validator" />    
    <!-- 转换器服务工厂Bean -->
    <bean id="conversion-service"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.neuedu.crm.utils.DateConverter" />
            </set>
        </property>
    </bean>

还可以实现更加复杂的时间格式转换,这里不演示了。

猜你喜欢

转载自blog.csdn.net/chenxihua1/article/details/82458350
今日推荐