Java LocalTime Create asLocalTime(Date date)

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

Description

Obtains an instance of LocalTime from a date object.

License

Apache License

Parameter

Parameter Description
date the date object to convert, not null

Return

the local time, not null

Declaration

public static LocalTime asLocalTime(Date date) 

Method Source Code


//package com.java2s;
/*//  w w  w .ja  v  a  2 s.  c om
 * 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.sql.Time;

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

public class Main {
    /**
     * Obtains an instance of {@code LocalTime} from a date object.
     * <p>
     * If the date object is an instance of {@link java.sql.Time}, then {@link java.sql.Time#toLocalTime()} is used.
     * Otherwise {@code LocalTime} is obtained by converting {@code Instant} at {@link ZoneId#systemDefault()}
     * to {@code LocalTime}.
     *
     * @param date the date object to convert, not null
     * @return the local time, not null
     */
    public static LocalTime asLocalTime(Date date) {
        return asLocalTime(date, getDefaultTimeZone());
    }

    /**
     * Obtains an instance of {@code LocalTime} from a date object.
     * <p>
     * If the date object is an instance of {@link java.sql.Time}, then {@link java.sql.Time#toLocalTime()} is used.
     * Otherwise {@code LocalTime} is obtained by converting {@code Instant} at {@link ZoneId#systemDefault()}
     * to {@code LocalTime}.
     *
     * @param date   the date object to convert, not null
     * @param zoneId the time zone id, not null
     * @return the local time, not null
     */
    public static LocalTime asLocalTime(Date date, ZoneId zoneId) {
        return date instanceof Time ? ((Time) date).toLocalTime() : date.toInstant().atZone(zoneId).toLocalTime();
    }

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

Related

  1. toLocalTime(java.sql.Time t)
  2. toLocalTime(java.sql.Time time)