Java examples for java.util:Month
Checks whether the given day, month and year combination is a valid date or not.
//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(isValidDate(year, month, day)); }// w w w.ja v a 2s . co m /** * Checks whether the given day, month and year combination is a valid date * or not. * * @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 True if the given day, month and year combination is a valid * date. */ public static boolean isValidDate(int year, int month, int day) { return isValidDate(year, month, day, 0, 0, 0); } /** * Checks whether the given day, month, year, hour, minute and second * combination is a valid date or not. * * @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 True if the given day, month, year, hour, minute and second * combination is a valid date. */ public static boolean isValidDate(int year, int month, int day, int hour, int minute, int second) { try { getValidCalendar(year, month, day, hour, minute, second); return true; } catch (IllegalArgumentException e) { return false; } } /** * 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; } }