Here you can find the source of asUtilDate(Object date, ZoneId zone)
Parameter | Description |
---|---|
zone | Time zone, used only if the input object is LocalDate or LocalDateTime. |
public static java.util.Date asUtilDate(Object date, ZoneId zone)
//package com.java2s; /*// w w w . j av a 2 s.c om * Copyright 2016 berni. * * 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.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class Main { /** * Calls {@link #asUtilDate(Object, ZoneId)} with the system default time * zone. */ public static java.util.Date asUtilDate(Object date) { return asUtilDate(date, ZoneId.systemDefault()); } /** * Creates a {@link java.util.Date} from various date objects. Is null-safe. * Currently supports:<ul> * <li>{@link java.util.Date} * <li>{@link java.sql.Date} * <li>{@link java.sql.Timestamp} * <li>{@link java.time.LocalDate} * <li>{@link java.time.LocalDateTime} * <li>{@link java.time.ZonedDateTime} * <li>{@link java.time.Instant} * </ul> * * @param zone Time zone, used only if the input object is LocalDate or * LocalDateTime. * * @return {@link java.util.Date} (exactly this class, not a subclass, such * as java.sql.Date) */ public static java.util.Date asUtilDate(Object date, ZoneId zone) { if (date == null) { return null; } if (date instanceof java.sql.Date || date instanceof java.sql.Timestamp) { return new java.util.Date(((java.util.Date) date).getTime()); } if (date instanceof java.util.Date) { return (java.util.Date) date; } if (date instanceof LocalDate) { return java.util.Date.from(((LocalDate) date).atStartOfDay(zone).toInstant()); } if (date instanceof LocalDateTime) { return java.util.Date.from(((LocalDateTime) date).atZone(zone).toInstant()); } if (date instanceof ZonedDateTime) { return java.util.Date.from(((ZonedDateTime) date).toInstant()); } if (date instanceof Instant) { return java.util.Date.from((Instant) date); } throw new UnsupportedOperationException( "Don't know hot to convert " + date.getClass().getName() + " to java.util.Date"); } }