方法一:
1,自定义日期转换器
public class DataConvert implements Converter<String, Date> {
/***
* 配置时间转换类
* @param date
* @return
*/
@Override
public Date convert(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2.配置自定义类型转换器
<!--注解驱动--> <mvc:annotation-driven conversion-service="format"/> <!-- 配置转换器 --> <bean id="format" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.itheima.user.controller.DataConvert"></bean> </set> </property> </bean>
3,在实体Bean上添加@DateTimeFormat,同时记得添加时间格式
@DateTimeFormat(pattern="yyyy-MM-dd") private Date date;
4,不要忘记了添加注解驱动
<mvc:annotation-driven conversion-service="format"/>
方式二,
@InitBinder进行时间转换
创建一个BaseController,在里面创建一个方法,加上@InitBinder注解,对入参为yyyy-MM-dd HH:mm:ss格式的数据进行格式化,将他们转成时间类型。
public class BaseController {
@InitBinder
protected void initBinder(WebDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
}
}
@DateTimeFormat(pattern="yyyy-MM-dd") private Date date;