首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将Vaadin DateField绑定到LocalDateTime

如何将Vaadin DateField绑定到LocalDateTime
EN

Stack Overflow用户
提问于 2016-05-15 09:11:26
回答 2查看 2.6K关注 0票数 3

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

EN

Stack Overflow用户

发布于 2021-11-10 08:11:25

这将是一个从LocalDate到LocalDateTime的Vaadin 8转换器:

代码语言:javascript
运行
复制
package de.company.project.portal.application.views.documents;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;

/**
 * A converter that converts between <code>LocalDate</code> and
 * <code>LocalDateTime</code>.
 *
 * Created from Vaadin v.8.13.0 LocalDateTimeToDateConverter
 */
public class LocalDateToLocalDateTimeConverter
        implements Converter<LocalDate, LocalDateTime>
{
    private ZoneId zoneId;

    /**
     * Creates a new converter using the given time zone.
     *
     * @param zoneId
     *            the time zone to use, not <code>null</code>
     */
    public LocalDateToLocalDateTimeConverter(ZoneId zoneId) {
        this.zoneId = Objects.requireNonNull(zoneId,
                "Zone identifier cannot be null");
    }


    @Override
    /** @return LocalDateTime from LocalDate with atTime(0,0,0,0) */
    public Result<LocalDateTime> convertToModel(LocalDate localDate,
                                                ValueContext context)
    {
        if (localDate == null) {
            return Result.ok(null);
        }
        return Result.ok(LocalDateTime.from(localDate.atTime(0,0,0,0))); //(hrs, mins, sec, nano sec)
    }


    @Override
    public LocalDate convertToPresentation(LocalDateTime localDateTime,
                                           ValueContext context)
    {
        if (localDateTime == null) {
            return null;
        }
        return LocalDate.from(localDateTime.atZone(zoneId));
    }

}

DTO DocumentDto在粘合剂中的使用:

代码语言:javascript
运行
复制
public void bindCreationDate(DateField field) {
    forField(field.getField())
            .withConverter(new LocalDateToLocalDateTimeConverter(ZoneId.systemDefault()))
            .bind(DocumentDto::getCreationDate, DocumentDto::setCreationDate);
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37236457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档