Vaadin docs展示如何将DateField
与java.util.Date
一起使用,但我希望将DateField
与BeanFieldGroup
绑定到Java的bean属性8类型java.time.LocalDateTime
。我怎样才能做到这一点?
答案 0 :(得分:4)
似乎可以选择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
之间进行转化。转换器需要通过DateField
或converter factory设置为setConverter
。