1 16 package net.sf.dozer.util.mapping.converters; 17 18 import java.lang.reflect.Constructor ; 19 import java.text.DateFormat ; 20 import java.text.ParseException ; 21 import java.util.Calendar ; 22 23 import org.apache.commons.beanutils.Converter; 24 25 28 public class DateConverter implements Converter { 29 private DateFormat dateFormat; 30 31 public DateConverter(DateFormat dateFormat) { 32 this.dateFormat = dateFormat; 33 } 34 35 public Object convert(Class destClass, Object sourceObj) { 36 Object result = null; 37 38 Class sourceFieldClass = sourceObj.getClass(); 39 long time = -1; 40 if (Calendar .class.isAssignableFrom(sourceFieldClass)) { 42 Calendar inVal = (Calendar ) sourceObj; 43 time = inVal.getTime().getTime(); 44 } else if (java.util.Date .class.isAssignableFrom(sourceFieldClass)) { 46 time = ( (java.util.Date ) sourceObj).getTime(); 47 } else if (dateFormat != null && String .class.isAssignableFrom(sourceObj.getClass())) { 49 try { 50 if("".equals(sourceObj)){ 51 return null; 52 } 53 time = dateFormat.parse( (String ) sourceObj).getTime(); 54 } catch (ParseException e) { 55 throw new ConversionException("Unable to parse source object using specified date format", e); 56 } 57 } else { 59 try { 60 time = Long.parseLong(sourceObj.toString()); 61 } catch (NumberFormatException e) { 62 throw new ConversionException("Unable to determine time in millis of source object",e); 63 } 64 } 65 66 try { 67 Constructor constructor = destClass.getConstructor(new Class [] {Long.TYPE}); 68 result = constructor.newInstance(new Object [] {new Long (time)}); 69 } catch (Exception e) { 70 throw new ConversionException(e); 71 } 72 73 return result; 74 75 } 76 77 public DateFormat getDateFormat() { 78 return dateFormat; 79 } 80 81 public void setDateFormat(DateFormat dateFormat) { 82 this.dateFormat = dateFormat; 83 } 84 } 85 | Popular Tags |