方法一:实体类中加日期格式化注解
@DateTimeFormat(pattern = "yyyy-MM-dd") //如果为具体的时分秒(pattern="yyyy-MM-dd HH:mm:ss)
private Date currentDay;
这种方法配置过于麻烦,推荐使用第三种
方法二:控制器Action中加入一段数据绑定代码
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
@Controller
@RequestMapping("user")
public class MyController extends MultiActionController{
@InitBinder
public void init(WebDataBinder dataBinder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor dateEditor = new CustomDateEditor(dateFormat,true);
dataBinder.registerCustomEditor(Date.class, dateEditor);
}
@RequestMapping("date")
public ModelAndView date(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String ss = dateFormat.format(date);
ModelAndView mv = new ModelAndView();
mv.addObject("date", ss);
mv.setViewName("MyJsp");
return mv;
}
}
方法三:实现一个全局日期类型转换器并进行配置
public class CustomDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
//进行日期转换
System.out.println(source);
if(source.length()>10){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
}else{
return new SimpleDateFormat("yyyy-MM-dd").parse(source);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
通过对日期的长度判断,这样两种类型的日期都能处理了
此时注意在springmvc.xml文件中进行一下配置
<!-- 配置自定义转换器 注意: 一定要将自定义的转换器配置到注解驱动上 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 指定自定义转换器的全路径名称 -->
<bean class="cm.cn.convert.DateConverter" />
</set>
</property>
</bean>