SpringMVC写一个时间格式转换器(三种方法)
第一种方法:
在变量处直接添加@DateTimeFormat(pattern="yyyy-MM-dd")

第二种方法:
1.首先新建一个DataConverter实现Converter接口的工具类
package util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.springframework.core.convert.converter.Converter;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class DataConverter implements Converter<String, Date> {
public Date convert(String source) {
//编写时间转换器,支持多种时间格式
SimpleDateFormat sdf = getSimpleDateFormat(source);
try {
Date date = sdf.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
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;
}
}
2.在配合文件中加上
<!-- 注册转化器 -->
<mvc:annotation-driven conversion-service="conversion-service"/>
<!-- 转换器服务工厂Bean -->
<bean id="conversion-service"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="util.DataConverter" /><!--工具类的class路径-->
</set>
</property>
</bean>
第三种方法:
1,首先建工具类
package util;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
public class MyDateConverter {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
2.让controller继承上面这个类

浙公网安备 33010602011771号