1 package org.restafarian.core.utils;
2
3 import java.sql.Timestamp;
4 import java.text.DateFormat;
5 import java.text.ParseException;
6 import java.text.SimpleDateFormat;
7 import java.util.Date;
8
9 import org.apache.commons.beanutils.ConversionException;
10 import org.apache.commons.beanutils.Converter;
11
12 /***
13 * <p>Converts java Date objects to ISO8601-compliant String values and back.</p>
14 */
15 public class ISO8601DateConverter implements Converter {
16 private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
17
18 public Object convert(Class clazz, Object object) throws ConversionException {
19 Object returnValue = null;
20
21 if (object != null) {
22 if (clazz == null) {
23 throw new ConversionException("Class parameter cannot be null.");
24 } else {
25 if (clazz.equals(Date.class) && object.getClass().equals(String.class)) {
26 returnValue = convertStringToDate((String) object);
27 } else if (clazz.equals(String.class)) {
28 if (object.getClass().equals(Date.class) || object.getClass().equals(Timestamp.class)) {
29 returnValue = convertDateToString((Date) object);
30 } else {
31 returnValue = object.toString();
32 }
33 } else {
34 returnValue = object;
35 }
36 }
37 }
38
39 return returnValue;
40 }
41
42 public Date convertStringToDate(String string) throws ConversionException {
43 try {
44 return FORMAT.parse(string);
45 } catch (ParseException e) {
46 throw new ConversionException(e);
47 }
48 }
49
50 public String convertDateToString(Date date) throws ConversionException {
51 String string = FORMAT.format(date);
52 return string.substring(0, string.length() - 2) + ":" + string.substring(string.length() - 2);
53 }
54 }