All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.vaadin.data.converter.LocalDateToDateConverter Maven / Gradle / Ivy

There is a newer version: 8.27.3
Show newest version
/*
 * Copyright (C) 2000-2024 Vaadin Ltd
 *
 * This program is available under Vaadin Commercial License and Service Terms.
 *
 * See  for the full
 * license.
 */
package com.vaadin.data.converter;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
import com.vaadin.ui.DateField;
import com.vaadin.ui.InlineDateField;

/**
 * A converter that converts between LocalDate and
 * Date. This is used when a {@link DateField} or
 * {@link InlineDateField} is bound to a {@link Date} property.
 *
 * @author Vaadin Ltd
 * @since 8.0
 */
public class LocalDateToDateConverter implements Converter {

    private ZoneId zoneId;

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

    /**
     * Creates a new converter using the system's default time zone.
     *
     * @see ZoneId#systemDefault()
     */
    public LocalDateToDateConverter() {
        this(ZoneId.systemDefault());
    }

    @Override
    public Result convertToModel(LocalDate localDate,
            ValueContext context) {
        if (localDate == null) {
            return Result.ok(null);
        }

        return Result.ok(Date.from(localDate.atStartOfDay(zoneId).toInstant()));
    }

    @Override
    public LocalDate convertToPresentation(Date date, ValueContext context) {
        if (date == null) {
            return null;
        }

        return Instant.ofEpochMilli(date.getTime()).atZone(zoneId)
                .toLocalDate();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy