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

Java examples for java.sql:Date

Description

Convert a calendar to a java.sql.Date.

Demo Code


//package com.java2s;
import java.time.LocalDateTime;

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  www .ja  v  a2s  .  c o  m
     * Convert a calendar to a java.sql.Date.
     * <p>
     * Note: sql.Date has no time, precision loss inevitable.
     *
     * @param calendar the instance to convert.
     * @return a Date representing the same time as the calendar.
     */
    public static java.sql.Date toSqlDate(final Calendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException(CALENDAR_MAY_NOT_BE_NULL);
        }
        return new java.sql.Date(calendar.getTimeInMillis());
    }

    /**
     * Convert a LocalDateTime to an sql.Date.
     * <p>
     * Note: sql.Date has no time, precision loss inevitable.
     *
     * @param localDateTime the instance to convert.
     * @return a Date representing the same time as the LocalDateTime.
     */
    public static java.sql.Date toSqlDate(final LocalDateTime localDateTime) {
        if (localDateTime == null) {
            throw new IllegalArgumentException(
                    LOCAL_DATE_TIME_MAY_NOT_BE_NULL);
        }
        return java.sql.Date.valueOf(localDateTime.toLocalDate());
    }

    /**
     * Convert an util.Date to an sql.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.sql.Date toSqlDate(final java.util.Date date) {
        if (date == null) {
            throw new IllegalArgumentException(DATE_MAY_NOT_BE_NULL);
        }
        return new java.sql.Date(date.getTime());
    }
}

Related Tutorials