1 24 package org.riotfamily.common.beans.propertyeditors; 25 26 import java.beans.PropertyEditorSupport ; 27 import java.text.DateFormat ; 28 import java.text.ParseException ; 29 import java.text.SimpleDateFormat ; 30 import java.util.Date ; 31 32 import org.springframework.util.StringUtils; 33 34 40 public class SqlDateEditor extends PropertyEditorSupport { 41 42 private final DateFormat dateFormat; 43 44 private final boolean allowEmpty; 45 46 private final int exactDateLength; 47 48 52 public SqlDateEditor() { 53 this(new SimpleDateFormat ("yyyy-MM-dd"), true, 10); 54 } 55 56 65 public SqlDateEditor(DateFormat dateFormat, boolean allowEmpty) { 66 this.dateFormat = dateFormat; 67 this.allowEmpty = allowEmpty; 68 this.exactDateLength = -1; 69 } 70 71 86 public SqlDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) { 87 this.dateFormat = dateFormat; 88 this.allowEmpty = allowEmpty; 89 this.exactDateLength = exactDateLength; 90 } 91 92 93 96 public void setAsText(String text) throws IllegalArgumentException { 97 if (this.allowEmpty && !StringUtils.hasText(text)) { 98 setValue(null); 100 } 101 else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) { 102 throw new IllegalArgumentException ( 103 "Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); 104 } 105 else { 106 try { 107 setValue(new java.sql.Date (this.dateFormat.parse(text).getTime())); 108 } 109 catch (ParseException ex) { 110 throw new IllegalArgumentException ("Could not parse date: " + ex.getMessage()); 111 } 112 } 113 } 114 115 118 public String getAsText() { 119 Date value = (Date ) getValue(); 120 return (value != null ? this.dateFormat.format(value) : ""); 121 } 122 123 } 124 | Popular Tags |