1 package org.appfuse.util; 2 3 import java.text.DateFormat ; 4 import java.text.SimpleDateFormat ; 5 6 import java.util.Date ; 7 import java.sql.Timestamp ; 8 9 import org.apache.commons.beanutils.ConversionException; 10 import org.apache.commons.beanutils.Converter; 11 import org.apache.commons.lang.StringUtils; 12 13 14 24 public class DateConverter implements Converter { 25 26 public Object convert(Class type, Object value) { 27 if (value == null) { 28 return null; 29 } else if (type == Timestamp .class) { 30 return convertToDate(type, value, DateUtil.getDateTimePattern()); 31 } else if (type == Date .class) { 32 return convertToDate(type, value, DateUtil.getDatePattern()); 33 } else if (type == String .class) { 34 return convertToString(type, value); 35 } 36 37 throw new ConversionException("Could not convert " + 38 value.getClass().getName() + " to " + 39 type.getName()); 40 } 41 42 protected Object convertToDate(Class type, Object value, String pattern) { 43 DateFormat df = new SimpleDateFormat (pattern); 44 if (value instanceof String ) { 45 try { 46 if (StringUtils.isEmpty(value.toString())) { 47 return null; 48 } 49 50 Date date = df.parse((String ) value); 51 if (type.equals(Timestamp .class)) { 52 return new Timestamp (date.getTime()); 53 } 54 return date; 55 } catch (Exception pe) { 56 pe.printStackTrace(); 57 throw new ConversionException("Error converting String to Date"); 58 } 59 } 60 61 throw new ConversionException("Could not convert " + 62 value.getClass().getName() + " to " + 63 type.getName()); 64 } 65 66 protected Object convertToString(Class type, Object value) { 67 68 if (value instanceof Date ) { 69 DateFormat df = new SimpleDateFormat (DateUtil.getDatePattern()); 70 if (value instanceof Timestamp ) { 71 df = new SimpleDateFormat (DateUtil.getDateTimePattern()); 72 } 73 74 try { 75 return df.format(value); 76 } catch (Exception e) { 77 e.printStackTrace(); 78 throw new ConversionException("Error converting Date to String"); 79 } 80 } else { 81 return value.toString(); 82 } 83 } 84 } 85 | Popular Tags |