Java SQL LocalDate asUtilDate(Object date)

Here you can find the source of asUtilDate(Object date)

Description

Calls #asUtilDate(Object,ZoneId) with the system default time zone.

License

Apache License

Declaration

public static Date asUtilDate(Object date) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.time.*;
import java.util.Date;

public class Main {
    /**//from   w  w w  . j a v  a  2  s .co  m
     * Calls {@link #asUtilDate(Object, ZoneId)} with the system default time zone.
     */
    public static Date asUtilDate(Object date) {
        return asUtilDate(date, ZoneId.systemDefault());
    }

    /**
     * Creates a {@link Date} from various date objects. Is null-safe. Currently supports:<ul>
     * <li>{@link 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 Date} (exactly this class, not a subclass, such as java.sql.Date)
     */
    public static Date asUtilDate(Object date, ZoneId zone) {
        if (date == null)
            return null;

        if (date instanceof java.sql.Date || date instanceof java.sql.Timestamp)
            return new Date(((Date) date).getTime());
        if (date instanceof Date)
            return (Date) date;
        if (date instanceof LocalDate)
            return Date.from(((LocalDate) date).atStartOfDay(zone).toInstant());
        if (date instanceof LocalDateTime)
            return Date.from(((LocalDateTime) date).atZone(zone).toInstant());
        if (date instanceof ZonedDateTime)
            return Date.from(((ZonedDateTime) date).toInstant());
        if (date instanceof Instant)
            return Date.from((Instant) date);

        throw new UnsupportedOperationException(
                "Don't know hot to convert " + date.getClass().getName() + " to java.util.Date");
    }
}

Related

  1. add(Date awal, int i)
  2. addDays(final Date date, final int daysToAdd)
  3. asLocalDate(Date date)
  4. asLocalDate(Date date)
  5. asLocalDate(java.util.Date date, ZoneId zone)
  6. asUtilDate(Object date, ZoneId zone)
  7. convertLocalDateToDatabaseDate(LocalDate localDate)
  8. getDay(Date date)
  9. getLastDate()