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

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

/*
 * 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.LocalDateTime;
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.DateTimeField;
import com.vaadin.ui.InlineDateTimeField;

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

    private ZoneId zoneId;

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

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

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

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

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

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy