KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > appfuse > util > TimestampConverter


1 package org.appfuse.util;
2
3 import java.text.DateFormat JavaDoc;
4 import java.text.SimpleDateFormat JavaDoc;
5 import java.util.Date JavaDoc;
6
7 import org.apache.commons.beanutils.ConversionException;
8 import org.apache.commons.lang.StringUtils;
9
10 /**
11  * This class is converts a java.util.Date to a String and a String to a
12  * java.util.Date for use as a Timestamp. It is used by BeanUtils when copying
13  * properties.
14  *
15  * <p>
16  * <a HREF="TimestampConverter.java.htm"><i>View Source</i></a>
17  * </p>
18  *
19  * @author <a HREF="mailto:dan@getrolling.com">Dan Kibler</a>
20  */

21 public class TimestampConverter extends DateConverter {
22     public static final String JavaDoc TS_FORMAT = DateUtil.getDatePattern() + " HH:mm:ss.S";
23
24     protected Object JavaDoc convertToDate(Class JavaDoc type, Object JavaDoc value) {
25         DateFormat JavaDoc df = new SimpleDateFormat JavaDoc(TS_FORMAT);
26         if (value instanceof String JavaDoc) {
27             try {
28                 if (StringUtils.isEmpty(value.toString())) {
29                     return null;
30                 }
31
32                 return df.parse((String JavaDoc) value);
33             } catch (Exception JavaDoc pe) {
34                 throw new ConversionException("Error converting String to Timestamp");
35             }
36         }
37
38         throw new ConversionException("Could not convert "
39                 + value.getClass().getName() + " to " + type.getName());
40     }
41
42     protected Object JavaDoc convertToString(Class JavaDoc type, Object JavaDoc value) {
43         DateFormat JavaDoc df = new SimpleDateFormat JavaDoc(TS_FORMAT);
44         if (value instanceof Date JavaDoc) {
45             try {
46                 return df.format(value);
47             } catch (Exception JavaDoc e) {
48                 throw new ConversionException("Error converting Timestamp to String");
49             }
50         }
51
52         return value.toString();
53     }
54 }
Popular Tags