/** * Convert a date to a String and a String to a Date * * @param type String, Date or Timestamp * @param value value to convert * @return Converted value for property population */ public Object convert(Class type, Object value) { if (value == null) { return null; } else if (type == Timestamp.class) { return convertToDate(type, value, DateUtil.getDateTimePattern()); } else if (type == Date.class) { return convertToDate(type, value, DateUtil.getDatePattern()); } else if (type == String.class) { return convertToString(type, value); } throw new ConversionException( "Could not convert " + value.getClass().getName() + " to " + type.getName()); }
/** * Convert a java.util.Date or a java.sql.Timestamp to a String. Or does a toString * * @param value value to convert * @return Converted value for property population */ protected Object convertToString(final Object value) { if (value instanceof Date) { DateFormat df = new SimpleDateFormat(DateUtil.getDatePattern()); if (value instanceof Timestamp) { df = new SimpleDateFormat(DateUtil.getDateTimePattern()); } try { return df.format(value); } catch (final Exception e) { throw new ConversionException("Error converting Date to String", e); } } else { return value.toString(); } }
/** * Convert a java.util.Date to a String * * @param type Date or Timestamp * @param value value to convert * @return Converted value for property population */ protected Object convertToString(Class type, Object value) { if (value instanceof Date) { DateFormat df = new SimpleDateFormat(DateUtil.getDatePattern()); if (value instanceof Timestamp) { df = new SimpleDateFormat(DateUtil.getDateTimePattern()); } try { return df.format(value); } catch (Exception e) { e.printStackTrace(); throw new ConversionException("Error converting Date to String"); } } else { return value.toString(); } }
@Test public void testConvertTimestampToString() throws Exception { final Timestamp timestamp = Timestamp.valueOf("2005-03-10 01:02:03.4"); final String time = (String) converter.convert(String.class, timestamp); assertEquals(DateUtil.getDateTime(DateUtil.getDateTimePattern(), timestamp), time); }