Java Calendar Create getCalendar(int year, int month, int day)

Here you can find the source of getCalendar(int year, int month, int day)

Description

Get Calendar instance by specified year, month and day.

License

Apache License

Parameter

Parameter Description
year 4-digit year.
month Month range is 1-12.
day Day range is 1-?, end depends on year and month.

Return

A Calendar instance.

Declaration

public static Calendar getCalendar(int year, int month, int day) 

Method Source Code

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

import java.util.Calendar;

public class Main {
    private static final int[] DAYS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    /**/*from   w  w  w.  j av  a 2 s.  co  m*/
     * Get Calendar instance by specified year, month and day.
     * 
     * @param year 4-digit year.
     * @param month Month range is 1-12.
     * @param day Day range is 1-?, end depends on year and month.
     * @return A Calendar instance.
     */
    public static Calendar getCalendar(int year, int month, int day) {
        if (year < 2000 || year > 2100)
            throw new IllegalArgumentException();
        if (month < 1 || month > 12)
            throw new IllegalArgumentException();
        if (day < 1)
            throw new IllegalArgumentException();
        if (month == 2 && isLeapYear(year)) {
            if (day > 29)
                throw new IllegalArgumentException();
        } else {
            if (day > DAYS[month - 1])
                throw new IllegalArgumentException();
        }
        month--;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c;
    }

    public static boolean isLeapYear(int year) {
        if (year % 100 == 0) {
            return year % 400 == 0;
        }
        return year % 4 == 0;
    }
}

Related

  1. getCalendar(final long timeInMillis)
  2. getCalendar(final String isodate)
  3. getCalendar(int d, int m, int y)
  4. getCalendar(int dayOfWeek, int atHour, int atMinute)
  5. getCalendar(int year, int month, int date)
  6. getCalendar(int year, int month, int day)
  7. getCalendar(int year, int month, int day, int hour, int min, int sec, String timezone)
  8. getCalendar(int year, int month, int day, int hour, int mins, int secs)
  9. getCalendar(int year, int month, int day, int hours, int minutes, int seconds, TimeZone tz)