Convert a calendar to a java.util.Date. - Java java.util

Java examples for java.util:Calendar

Description

Convert a calendar to a java.util.Date.

Demo Code


//package com.java2s;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;

public class Main {
    public static final String DATE_MAY_NOT_BE_NULL = "Date may not be null";
    public static final String CALENDAR_MAY_NOT_BE_NULL = "Calendar may not be null";
    public static final String LOCAL_DATE_TIME_MAY_NOT_BE_NULL = "LocalDateTime may not be null";

    /**//from ww w .j  a v  a 2  s .  c om
     * Convert a calendar to a java.util.Date.
     * <p>
     * Essentially nothing more than Calendar.getTime()
     *
     * @param calendar the instance to convert.
     * @return a Date representing the same time as the calendar.
     * @see Calendar#getTime()
     */
    public static java.util.Date toDate(final Calendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException(CALENDAR_MAY_NOT_BE_NULL);
        }
        return calendar.getTime();
    }

    /**
     * Convert a LocalDateTime to a java.util.Date.
     *
     * @param localDateTime the instance to convert.
     * @return a Date representing the same time as the LocalDateTime.
     */
    public static java.util.Date toDate(final LocalDateTime localDateTime) {
        if (localDateTime == null) {
            throw new IllegalArgumentException(
                    LOCAL_DATE_TIME_MAY_NOT_BE_NULL);
        }
        return java.util.Date.from(localDateTime.atZone(
                ZoneId.systemDefault()).toInstant());
    }

    /**
     * Convert a java.sql.Date to a java.util.Date.
     * <p>
     * Note: sql.Date has no time, precision loss inevitable.
     *
     * @param date the instance to convert.
     * @return a Date representing the same time as the Date.
     */
    public static java.util.Date toDate(final java.sql.Date date) {
        if (date == null) {
            throw new IllegalArgumentException(DATE_MAY_NOT_BE_NULL);
        }
        return new java.util.Date(date.getTime());
    }
}

Related Tutorials