Java LocalDateTime Create asLocalDateTime(Date date)

Here you can find the source of asLocalDateTime(Date date)

Description

Obtains an instance of LocalDateTime from a date object.

License

Apache License

Parameter

Parameter Description
date the date object to convert, not null

Return

the local date-time, not null

Declaration

public static LocalDateTime asLocalDateTime(Date date) 

Method Source Code

//package com.java2s;
/*/*from  w  w w  .ja v  a 2  s . co m*/
 * Copyright (c) 2008-2018 Haulmont.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

public class Main {
    /**
     * Obtains an instance of {@code LocalDateTime} from a date object.
     * <p>
     * {@code LocalDate} is obtained by converting {@code Instant} at {@link ZoneId#systemDefault()}
     * to {@code LocalDateTime}.
     *
     * @param date the date object to convert, not null
     * @return the local date-time, not null
     */
    public static LocalDateTime asLocalDateTime(Date date) {
        return asLocalDateTime(date, getDefaultTimeZone());
    }

    /**
     * Obtains an instance of {@code LocalDateTime} from a date object.
     * <p>
     * {@code LocalDate} is obtained by converting {@code Instant} at {@link ZoneId#systemDefault()}
     * to {@code LocalDateTime}.
     *
     * @param date   the date object to convert, not null
     * @param zoneId the time zone id, not null
     * @return the local date-time, not null
     */
    public static LocalDateTime asLocalDateTime(Date date, ZoneId zoneId) {
        if (date instanceof java.sql.Date) {
            LocalDate localDate = ((java.sql.Date) date).toLocalDate();
            return LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
        }
        return date.toInstant().atZone(zoneId).toLocalDateTime();
    }

    private static ZoneId getDefaultTimeZone() {
        // TODO: gg, return proper ZoneId
        return ZoneId.systemDefault();
    }
}

Related

  1. asLocalDateTime(Date date)
  2. getLocalDateTime(Date datetime, TimeZone timeZone)
  3. getLocalDateTimeFromEpochMilli(long epochMillis)
  4. getLocalDateTimeFromMillis(final long millis)