1 16 package net.sf.dozer.util.mapping.converters; 17 18 import java.text.DateFormat ; 19 import java.text.ParseException ; 20 import java.util.Calendar ; 21 import java.util.Date ; 22 import java.util.GregorianCalendar ; 23 24 import org.apache.commons.beanutils.Converter; 25 26 29 public class CalendarConverter implements Converter { 30 31 private DateFormat dateFormat; 32 33 public CalendarConverter(DateFormat dateFormat) { 34 this.dateFormat = dateFormat; 35 } 36 37 public Object convert(Class destClass, Object sourceObj) { 38 Calendar result = new GregorianCalendar (); 39 Class sourceFieldClass = sourceObj.getClass(); 40 if (java.util.Date .class.isAssignableFrom(sourceFieldClass)) { 42 result.setTime( (java.util.Date ) sourceObj); 43 } 44 else if (Calendar .class.isAssignableFrom(sourceFieldClass)) { 46 Calendar c = (Calendar ) sourceObj; 47 result.setTime(c.getTime()); 48 } 49 else if (dateFormat != null && String .class.isAssignableFrom(sourceFieldClass)) { 51 try { 52 result.setTime(new Date (dateFormat.parse( (String ) sourceObj).getTime())); 53 } catch (ParseException e) { 54 throw new ConversionException("Unable to parse source object using specified date format", e); 55 } 56 } else { 58 try { 59 result.setTime(new Date (Long.parseLong(sourceObj.toString()))); 60 } 61 catch (NumberFormatException e) { 62 throw new ConversionException("Unable to determine time in millis of source object", e); 63 } 64 } 65 return result; 66 } 67 68 public DateFormat getDateFormat() { 69 return dateFormat; 70 } 71 72 public void setDateFormat(DateFormat dateFormat) { 73 this.dateFormat = dateFormat; 74 } 75 } 76 | Popular Tags |