簡體   English   中英

表格中兩個相同類型的實體字段的格式不同

[英]Formatting two Entity fields of the same type differently in a table

我正在使用帶有實體類的JPA容器從MySQL填充表。 其中兩個字段是GregorianCalendar字段(一個是日期,一個是時間),我正在尋找一種單獨格式化/轉換它們的方式,以便日期顯示為短日期(例如dd-MM-yyyy),並且顯示時間根據語言環境在24小時內縮短(HH:mm)。

根據我的搜索結果,我了解格式化日期和時間的最佳方法是覆蓋默認表,因此,我已經這樣做了:

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);
            }

        };

並填充表:

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" });

第一個條件是應用的唯一條件,因為兩個字段都是GregorianCalendar的實例。 有沒有其他方法可以我參考這些字段,或者我可以有選擇地設置它們的格式,同時牢記它們都是同一類型?

我想說,最干凈的解決方案是創建兩個Converter ,然后將一個轉換器應用於列,如下所示:

table.setConverter("myPropertyId", new MyConverter());

這是有關Converter實現的示例:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM