1 package prefuse.data.parser; 2 3 import java.sql.Date ; 4 import java.text.DateFormat ; 5 import java.text.ParsePosition ; 6 7 18 public class DateParser implements DataParser { 19 20 protected DateFormat m_dfmt; 21 protected ParsePosition m_pos; 22 23 26 public DateParser() { 27 this(DateFormat.getDateInstance(DateFormat.SHORT)); 28 } 29 30 34 public DateParser(DateFormat dateFormat) { 35 m_dfmt = dateFormat; 36 m_pos = new ParsePosition (0); 37 } 38 39 43 public Class getType() { 44 return Date .class; 45 } 46 47 50 public String format(Object value) { 51 return value==null ? null : m_dfmt.format(value); 52 } 53 54 57 public boolean canParse(String text) { 58 try { 59 parseDate(text); 60 return true; 61 } catch ( DataParseException e ) { 62 return false; 63 } 64 } 65 66 69 public Object parse(String text) throws DataParseException { 70 return parseDate(text); 71 } 72 73 79 public Date parseDate(String text) throws DataParseException { 80 m_pos.setErrorIndex(0); 81 m_pos.setIndex(0); 82 83 Date d = null; 85 try { 86 d = Date.valueOf(text); 87 m_pos.setIndex(text.length()); 88 } catch ( IllegalArgumentException e ) { 89 d = null; 90 } 91 if ( d == null ) { 92 java.util.Date d1 = m_dfmt.parse(text, m_pos); 93 if ( d1 != null ) { 94 d = new Date (d1.getTime()); 95 } 96 } 97 98 if ( d == null || m_pos.getIndex() < text.length() ) { 101 throw new DataParseException("Could not parse Date: "+text); 102 } else { 103 return d; 104 } 105 } 106 107 } | Popular Tags |