zoukankan      html  css  js  c++  java
  • spring 日期转换

    public class DateEditor extends PropertyEditorSupport {  
          
        private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
      
        private DateFormat dateFormat;  
        private boolean allowEmpty = true;  
      
        public DateEditor() {  
        }  
      
        public DateEditor(DateFormat dateFormat) {  
            this.dateFormat = dateFormat;  
        }  
      
        public DateEditor(DateFormat dateFormat, boolean allowEmpty) {  
            this.dateFormat = dateFormat;  
            this.allowEmpty = allowEmpty;  
        }  
      
        /** 
         * Parse the Date from the given text, using the specified DateFormat. 
         */  
        @Override  
        public void setAsText(String text) throws IllegalArgumentException {  
            if (this.allowEmpty && !StringUtils.hasText(text)) {  
                // Treat empty String as null value.  
                setValue(null);  
            } else {  
                try {  
                    if(this.dateFormat != null)  
                        setValue(this.dateFormat.parse(text));  
                    else {                       
                        setValue(TIMEFORMAT.parse(text));                     
                    }  
                } catch (ParseException ex) {  
                    throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);  
                }  
            }  
        }  
      
        /** 
         * Format the Date as String, using the specified DateFormat. 
         */  
        @Override  
        public String getAsText() {  
            Date value = (Date) getValue();  
            DateFormat dateFormat = this.dateFormat;  
            if(dateFormat == null)  
                dateFormat = TIMEFORMAT;  
            return (value != null ? dateFormat.format(value) : "");  
        }  
    @InitBinder  
    protected void initBinder(HttpServletRequest request,  
                                 ServletRequestDataBinder binder) throws Exception {  
       //对于需要转换为Date类型的属性,使用DateEditor进行处理  
       binder.registerCustomEditor(Date.class, new DateEditor());  
    }
  • 相关阅读:
    【文言文】从高考到程序员
    lambda方法引用总结——烧脑吃透
    秒杀苹果carplay baidu车联网API冷艳北京车展
    东君误妾我怜卿(一)
    百度快照投诉技巧案例分析百度快照就是这样刷出来的
    新浪博客是否可以放谷歌广告?如何添加
    与葡萄酒的亲密接触-选购技巧篇
    车联网高速公路智能交通解决方案
    物联网细分领域-车联网(OBD)市场分析
    APP开发选择什么框架好? 请看这里!
  • 原文地址:https://www.cnblogs.com/leonkobe/p/3622355.html
Copyright © 2011-2022 走看看