Validate the actual date of the given date elements and returns a calendar instance based on the given date elements. - Java java.util

Java examples for java.util:Date Compare

Description

Validate the actual date of the given date elements and returns a calendar instance based on the given date elements.

Demo Code


//package com.java2s;
import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        int year = 2;
        int month = 2;
        int day = 2;
        System.out.println(getValidCalendar(year, month, day));
    }// w w  w.  j a va  2 s .co m

    /**
     * Validate the actual date of the given date elements and returns a
     * calendar instance based on the given date elements. The time is forced to
     * 00:00:00.
     *
     * @param year The year part of the date.
     * @param month The month part of the date.
     * @param day The day part of the date.
     * @return A Calendar instance prefilled with the given date elements.
     */
    public static Calendar getValidCalendar(int year, int month, int day) {
        return getValidCalendar(year, month, day, 0, 0, 0);
    }

    /**
     * Validate the actual date of the given date elements and returns a
     * calendar instance based on the given date elements.
     *
     * @param year The year part of the date.
     * @param month The month part of the date.
     * @param day The day part of the date.
     * @param hour The hour part of the date.
     * @param minute The minute part of the date.
     * @param second The second part of the date.
     * @return A Calendar instance prefilled with the given date elements.
     */
    public static Calendar getValidCalendar(int year, int month, int day,
            int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setLenient(false); // Don't automatically convert invalid date.
        calendar.set(year, month - 1, day, hour, minute, second);
        calendar.getTimeInMillis(); // Lazy update, throws
        // IllegalArgumentException if invalid date.
        return calendar;
    }
}

Related Tutorials