How to bind a Vaadin DateField to a LocalDateTime

微笑、不失礼 提交于 2019-12-11 02:08:00

问题


The Vaadin docs show how to use the DateField with java.util.Date but I want to bind the DateField with a BeanFieldGroup to a bean property of Java 8 type java.time.LocalDateTime. How can I achieve that?


回答1:


Seems like a Vaadin Converter is the way to go:

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

}

Inspired by this link which converts between LocalDate and Date. The converter needs to be set to the DateField via setConverter or alternatively via a converter factory.



来源:https://stackoverflow.com/questions/37236457/how-to-bind-a-vaadin-datefield-to-a-localdatetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!