2
的Vaadin docs展示瞭如何使用DateField
與java.util.Date
,但我想給DateField
與BeanFieldGroup
綁定到Java 8型java.time.LocalDateTime
的bean屬性。我怎樣才能做到這一點?如何將Vaadin的DateField綁定到LocalDateTime
的Vaadin docs展示瞭如何使用DateField
與java.util.Date
,但我想給DateField
與BeanFieldGroup
綁定到Java 8型java.time.LocalDateTime
的bean屬性。我怎樣才能做到這一點?如何將Vaadin的DateField綁定到LocalDateTime
似乎是一個Vaadin Converter是要走的路:
package org.raubvogel.fooddiary.util;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Locale;
import com.vaadin.data.util.converter.Converter;
/**
* Provides a conversion between old {@link Date} and new {@link LocalDateTime} API.
*/
public class LocalDateTimeToDateConverter implements Converter<Date, LocalDateTime> {
private static final long serialVersionUID = 1L;
@Override
public LocalDateTime convertToModel(Date value, Class<? extends LocalDateTime> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
if (value != null) {
return value.toInstant().atZone(ZoneOffset.systemDefault()).toLocalDateTime();
}
return null;
}
@Override
public Date convertToPresentation(LocalDateTime value, Class<? extends Date> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
if (value != null) {
return Date.from(value.atZone(ZoneOffset.systemDefault()).toInstant());
}
return null;
}
@Override
public Class<LocalDateTime> getModelType() {
return LocalDateTime.class;
}
@Override
public Class<Date> getPresentationType() {
return Date.class;
}
}
由this link這LocalDate
和Date
之間進行轉換的啓發。轉換器需要通過setConverter
或通過converter factory設置爲DateField
。
僅供參考:該轉換器現在是Vaadin 8中Binder的一部分,其接口已更改。 Vaadin 8現在帶有'LocalDate'和'LocalDateTime'的轉換器,日期字段現在依賴於新的日期類型。 –