如何将Vaadin DateField绑定到LocalDateTime

时间:2016-05-15 09:11:27

标签: vaadin vaadin7 jsr310

Vaadin docs展示如何将DateFieldjava.util.Date一起使用,但我希望将DateFieldBeanFieldGroup绑定到Java的bean属性8类型java.time.LocalDateTime。我怎样才能做到这一点?

1 个答案:

答案 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,可在LocalDateDate之间进行转化。转换器需要通过DateFieldconverter factory设置为setConverter