亲测有效
1创建日期格式话工具DateEditor
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;
/**
* 日期格式话工具
* SPRINGMVC日期字符换转换Date
* @author ALLEN
*/
publicclassDateEditor extends PropertyEditorSupport {
@Override
publicvoidsetAsText(String text)throwsIllegalArgumentException {
Date date = null;
try {
date=DateUtil.parseDate(text);
} catch (ParseException e) {
e.printStackTrace();
}
setValue(date);
}
}
2创建日期装配器
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
/**
* 日期装配器
* @author lxy
* @date 2017年3月23日下午2:15:43
*/
publicclassDateBinderUtil {
/**
* 初始化日期格式
*
* @param request
* @param binder
* @throws Exception
*/
@InitBinder
protectedvoidinitBinder(HttpServletRequest request, ServletRequestDataBinder binder) throwsException {
binder.registerCustomEditor(Date.class, new DateEditor());
}
}
3配置
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=utf-8</value>
</list>
</property>
</bean>
4附录DateUtil
// 从字符串中分析日期
publicstatic Date parseDate(String dateStr) throws ParseException {
Datedate= null;
String[]dateArray= dateStr.split("\\D+"); // +防止多个非数字字符在一起时导致解析错误
intdateLen = dateArray.length;
intdateStrLen = dateStr.length();
if (dateLen > 0) {
if (dateLen == 1 && dateStrLen > 4) {
if (dateStrLen == "yyyyMMddHHmmss".length()){
// 如果字符串长度为14位并且不包含其他非数字字符,则按照(yyyyMMddHHmmss)格式解析
date = parseDate(dateStr, "yyyyMMddHHmmss");
}elseif(dateStrLen== "yyyyMMddHHmm".length()) {
date = parseDate(dateStr, "yyyyMMddHHmm");
}elseif(dateStrLen== "yyyyMMddHH".length()) {
date = parseDate(dateStr, "yyyyMMddHH");
}elseif(dateStrLen== "yyyyMMdd".length()) {
date = parseDate(dateStr, "yyyyMMdd");
}elseif(dateStrLen== "yyyyMM".length()){
date = parseDate(dateStr, "yyyyMM");
}
}else{
StringfDateStr= dateArray[0];
for (inti = 1; i < dateLen; i++) {
// 左补齐是防止十位数省略的情况
fDateStr += leftPad(dateArray[i], "0", 2);
}
if (dateStr.trim().matches("^\\d{1,2}:\\d{1,2}(:\\d{1,2})?$")) {
// 补充年月日3个字段
dateLen += 3;
fDateStr = formatDate(new Date(), "yyyyMMdd")+ fDateStr;
}
date = parseDate(fDateStr, "yyyyMMddHHmmss".substring(0,(dateLen- 1) * 2 + 4));
}
}
returndate;
}