Vaadin docs显示如何将 DateField
与 java.util.Date
一起使用,但我想将 DateField
与 BeanFieldGroup
绑定(bind)到 Java 8 类型 java.time.LocalDateTime
的 bean 属性。我怎样才能做到这一点?
最佳答案
似乎是 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 - 如何将 Vaadin DateField 绑定(bind)到 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236457/