`
hy2012_campus
  • 浏览: 29524 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类
最新评论

springmvc中常用initDatabinder处理时间

 
阅读更多

对前端传过来的时间字符串,以及后端向前端传的字符串绑定时间参数:

import org.springframework.util.StringUtils;

public class DateConvertEditor extends PropertyEditorSupport {
    private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd" ); 
    public void setAsText(String text) throws IllegalArgumentException {
         if (StringUtils.hasText(text)) {
             try {
                 if (text.indexOf(":" ) == -1 && text.length() == 10) {
                    setValue( this.dateFormat .parse(text));
                } else if (text.indexOf(":") > 0 && text.length() == 19) {
                    setValue( this.datetimeFormat .parse(text));
                } else if (text.indexOf(":") > 0 && text.length() == 21) {
                    text = text.replace( ".0", "");
                    setValue( this.datetimeFormat .parse(text));
                } else {
                     throw new IllegalArgumentException(
                             "Could not parse date, date format is error ");
                }
            } catch (ParseException ex) {
                IllegalArgumentException iae = new IllegalArgumentException(
                         "Could not parse date: " + ex.getMessage());
                iae.initCause(ex);
                throw iae;
            }
        } else {
            setValue( null);
        }
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics