import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
- 自定义类型转换器
*/
public class DateConvert implements Converter<String, Date> {
@Override
public Date convert(String s) {
if (s == null || “”.equals(s)) {
return null;
}
DateFormat df = null;
try {
int i1 = s.indexOf("-") >= 0 ? s.indexOf("-") : s.indexOf("/") >= 0 ? s.indexOf("/") : -1;
int i2 = s.indexOf("😊 >= 0 ? s.indexOf("😊 : -1;
String strFormat = null;
if (i1 > -1 && i2 == -1) {
strFormat =“yyyy-MM-dd”;
} else if (i1 == -1 && i2 > -1) {
strFormat =“HH:mm:ss”;
} else if (i1 > -1 && i2 > -1) {
strFormat =“yyyy-MM-dd HH:mm:ss”;
}
System.out.println(strFormat);
df = new SimpleDateFormat(strFormat);
return df.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
dispatch-servlet.xml文件中增加以下内容:
<mvc:annotation-driven conversion-service=“formattingConversionService”/>
<!--声明格式转换服务工厂bean-->
<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean"
id="formattingConversionService">
<property name="converters">
<bean class="com.mvc1.handler2.DateConvert"></bean>
</property>
</bean>