I am using a JPA Container with Entity classes to populate a Table from MySQL. Two of the fields are GregorianCalendar fields (one is date and one is time) and I am looking for a way to format/convert them separately so that the date appears as a short date (e.g. dd-MM-yyyy) and the time appears as short 24h time (HH:mm) according to locale.
Based on my search results, I understand that the best way to format date and time is to override the default table so this is what I have done:
final Table opTable = new Table() {
private static final long serialVersionUID = 1L;
@Override
protected String formatPropertyValue(Object rowId, Object colId, Property property) {
Object v = property.getValue();
if (v instanceof GregorianCalendar) {
GregorianCalendar datez = (GregorianCalendar) v;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
String formattedDate = df.format(datez.getTime());
return formattedDate;
}
if (v instanceof GregorianCalendar) {
GregorianCalendar timeValue = (GregorianCalendar) v;
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
fmt.setCalendar(timeValue);
String timeFormatted = fmt.format(timeValue.getTime());
return timeFormatted;
}
return super.formatPropertyValue(rowId, colId, property);
}
};
And populating the Table:
bookings = JPAContainerFactory.make(BookingEntity.class, CSAdminUI.PERSISTENCE_UNIT);
opTable = new Table(null, bookings); opTable.setContainerDataSource(bookings);
opTable.setVisibleColumns(new Object[] { "operator.rowid", "activity.name", "startDate", "startTime", "done", "price", "operatorCost", "paymentType", "voucherCode", "hints", "timeLeft", "succeded", "teamPicture", "comment" });
The first condition is the only one being applied seeing as both fields are instances of GregorianCalendar. Is there another way I can refer to the fields or another way I can selectively format them keeping in mind they are both of the same type?
I would say that most cleanest solution is create two Converter
s, and then apply a converter to a column as follows:
table.setConverter("myPropertyId", new MyConverter());
Here's an example about a Converter
implementation:
public class MyConverter implements Converter<String, GregorianCalendar> {
@Override
public GregorianCalendar convertToModel(String value, Class<? extends GregorianCalendar> targetType, Locale locale) throws ConversionException {
throw new ConversionException("Converting from Presentation to Model is not supported.");
}
@Override
public String convertToPresentation(GregorianCalendar value, Class<? extends String> targetType, Locale locale) throws ConversionException {
// TODO do the conversion here
return null;
}
@Override
public Class<GregorianCalendar> getModelType() {
return GregorianCalendar.class;
}
@Override
public Class<String> getPresentationType() {
return String.class;
}
}