KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > util > DateConverter


1 /*
2  * (c) Rob Gordon 2005
3  */

4 package org.oddjob.util;
5
6 import java.text.ParseException JavaDoc;
7 import java.util.Date JavaDoc;
8
9 import org.apache.commons.beanutils.ConversionException;
10 import org.apache.commons.beanutils.Converter;
11
12 public class DateConverter implements Converter {
13
14     
15     public Object JavaDoc convert(Class JavaDoc type, Object JavaDoc value)
16     throws ConversionException {
17         if (value == null) {
18             return null;
19         }
20         if (String JavaDoc.class.equals(type) && value instanceof Date JavaDoc) {
21             return convertDate((Date JavaDoc) value);
22         }
23         else if (Date JavaDoc.class.equals(type) && value instanceof String JavaDoc) {
24             return convertString((String JavaDoc) value);
25         }
26         else {
27             throw new ConversionException("Can not convert from ["
28                     + value.getClass().getName() + "] to ["
29                     + type.getName() + "]");
30         }
31     }
32     
33     protected String JavaDoc convertDate(Date JavaDoc date) {
34         return DateHelper.formatDate(date);
35     }
36     
37     protected Date JavaDoc convertString(String JavaDoc text) {
38         try {
39             return DateHelper.parseDateTime(text);
40         } catch (ParseException JavaDoc e) {
41             throw new ConversionException(e);
42         }
43     }
44     
45 }
46
Popular Tags