Java 打印日历
import java.util.*;
public class ViewMonth {
int month; //该变量用于存储月
int year; //该变量用于存储年
public ViewMonth(final int dismonth, final int disyear) {
this.month = dismonth;
this.year = disyear;
}
//该方法返回月
public String checkMonth() {
String[] months = {"1 月", "2 月", "3 月", "4 月", "5 月", "6 月", "7 月",
"8 月", "9 月",
"10 月", "11 月", "12 月"};
return months[month];
}
//该方法返回天
public int checkDays() {
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[month];
}
//打印日历
public void print() {
int initSpace = 0; //将该月份起始的天数留空
try {
//获取月份名称
String monthName = checkMonth();
System.out.println("");
System.out.println(" " + year + "年" + monthName);
System.out.println("");
} catch (Exception ex) {
System.out.println("超出范围.....");
System.exit(0);
}
GregorianCalendar gc = new GregorianCalendar(year, month, 1);
System.out.println(" 日 一 二 三 四 五 六");
//得到该月的第一天是一个星期的第几天,然后预留空格
initSpace = gc.get(Calendar.DAY_OF_WEEK) - 1;
//获取天数
int daysInMonth = checkDays();
//检查是否为闰年,为二月份增加一天(使用 isLeapYear()方法判断是否为闰
年)
if (gc.isLeapYear(gc.get(Calendar.YEAR)) && month == 1) {
++daysInMonth;