//1900年到输入的年份当月的日历
public class CalendarMethod {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scan.nextInt();
System.out.println("请输入月份:");
int month = scan.nextInt();
printCalendar(year,month);
}
public static void printCalendar(int year,int month){
int totalDays = getTotalDays(year,month);
int temp = (totalDays + 1) % 7;
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for(int i=1; i<=temp; i++){
System.out.print("\t");
}
for(int i=1; i<=getMonthDay(year,month); i++){
System.out.print(i + "\t");
if( (totalDays + i + 1) % 7 == 0){
System.out.println();
}
}
}
//获取总天数
public static int getTotalDays(int year,int month){
int totalYearDays = getTotalYearDays(year);
int totalMonthDays = getTotalMonthDays(year,month);
int totalDays = totalYearDays + totalMonthDays;
return totalDays;
}
//获取制定年份月份之前的月份的总天数
private static int getTotalMonthDays(int year, int month) {
int totalMonthDays = 0;
for(int i=1; i<month; i++){
totalMonthDays += getMonthDay(year,i);
}
return totalMonthDays;
}
//获得你传入年份月份的天数
public static int getMonthDay(int year,int month){
boolean isRN = isRN(year);
int monthDay = 0;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
monthDay = 31;
break;
case 2:
if(isRN) monthDay = 29;
else monthDay = 28;
break;
default:
monthDay = 30;
break;
}
return monthDay;
}
//得到年份總天數的方法
public static int getTotalYearDays(int year) {
// 计算1900年至你输入的年份位置的总天数
int totalYearDays = 0;
for (int i = 1900; i < year; i++) {
if (isRN(i)) {
totalYearDays += 366;
} else {
totalYearDays += 365;
}
}
return totalYearDays;
}
public static boolean isRN(int year){
boolean isRN = false;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
isRN = true;
}
return isRN;
}
}