1 16 17 package org.springframework.beans.propertyeditors; 18 19 import java.beans.PropertyEditorSupport ; 20 import java.text.DateFormat ; 21 import java.text.ParseException ; 22 import java.util.Date ; 23 24 import org.springframework.util.StringUtils; 25 26 46 public class CustomDateEditor extends PropertyEditorSupport { 47 48 private final DateFormat dateFormat; 49 50 private final boolean allowEmpty; 51 52 private final int exactDateLength; 53 54 55 64 public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) { 65 this.dateFormat = dateFormat; 66 this.allowEmpty = allowEmpty; 67 this.exactDateLength = -1; 68 } 69 70 85 public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) { 86 this.dateFormat = dateFormat; 87 this.allowEmpty = allowEmpty; 88 this.exactDateLength = exactDateLength; 89 } 90 91 92 95 public void setAsText(String text) throws IllegalArgumentException { 96 if (this.allowEmpty && !StringUtils.hasText(text)) { 97 setValue(null); 99 } 100 else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) { 101 throw new IllegalArgumentException ( 102 "Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); 103 } 104 else { 105 try { 106 setValue(this.dateFormat.parse(text)); 107 } 108 catch (ParseException ex) { 109 throw new IllegalArgumentException ("Could not parse date: " + ex.getMessage()); 110 } 111 } 112 } 113 114 117 public String getAsText() { 118 Date value = (Date ) getValue(); 119 return (value != null ? this.dateFormat.format(value) : ""); 120 } 121 122 } 123 | Popular Tags |