Spring时间(Date)类型转换+自定义
第一种方法:利用内置的 CustomDateEditor(不推荐,每个类都需要定义)
首先,在我们的 Controller 的 InitBinder 里面,注册 CustomEditor
//首先初始化这个方法 @InitBinder public void init (WebDataBinder binder) { CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true); binder.registerCustomEditor(Date.class, dateEditor); }
当提交的时候,会进入
Spring配置Converter、Formatter日期转换
第二种方法:实现自定义 Converter或者Formatter<Date>
首先创建一个类继承Converter<String, Date>接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.maven1128.miscellanueous; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MuDateConverter implements Converter<String, Date> { @Override public Date convert(String value) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date=null; try { date = simpleDateFormat.parse(value); } catch (ParseException e) { e.printStackTrace(); } return date; } }
或者一个类继承Formatter<Date>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.maven1128.miscellanueous; import org.springframework.format.Formatter; import javax.xml.crypto.Data; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MDateFormatter implements Formatter<Date> { // 日期类型模板:如yyyy-MM-dd 默认 private String datePattern="yyyy-MM-dd"; // 日期格式化对象 private SimpleDateFormat dateFormat; // 构造器,通过依赖注入的日期类型创建日期格式化对象 public MDateFormatter(String datePattern){ super(); this.datePattern=datePattern; dateFormat = new SimpleDateFormat(datePattern); } @Override public String print(Date data, Locale locale) { dateFormat.setLenient(false); return dateFormat.format(data); } // 解析文本字符串返回一个Formatter<T>的T类型对象 @Override public Date parse(String text, Locale locale) throws ParseException { return dateFormat.parse(text); } }
接口
然后xml配置并注册 ConversionService:
converters
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<bean name="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.wbg.maven1128.miscellanueous.MuDateConverter" /> </set> </property> </bean> <!--启用--> <mvc:annotation-driven conversion-service="conversionService" />
factoryBean
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<bean name="factoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="com.wbg.maven1128.miscellanueous.MDateFormatter" > <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> </set> </property> </bean> <mvc:annotation-driven conversion-service="factoryBean"/>
提交的时候