首页 > 代码库 > 打印日历的方法
打印日历的方法
日历的简单实现方法
package ClassDemo; import java.util.Scanner; public class PrintMonthlyCalindar {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入年:");
int year = sc.nextInt();
System.out.print("请输入月:");
int month = sc.nextInt();
sc.close();
printMonth(year, month);
}
public static boolean isLeapYear(int year) {
return year % 400 == 0 || (0 == year % 4 && year % 100 != 0);
}
public static int getNumberOfDays (int year, int month) {
int numberOfdays = -1;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numberOfdays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numberOfdays = 30;
break;
case 2:
numberOfdays = (isLeapYear(year)) ? 29 : 28;
break;
default:
break;
}
return numberOfdays;
}
public static int getStartDay(int year, int month) {
final int START_DAY_JAN_1800 = 3;
int totalNumberOfDays = getTotalNumberOfDays(year, month);
return (totalNumberOfDays + START_DAY_JAN_1800) % 7;
}
private static int getTotalNumberOfDays(int year, int month) {
int totalDays = 0;
for (int i = 1800; i < year; i++) {
if (!isLeapYear(i))
totalDays += 365;
else
totalDays += 366;
}
for (int i = 1; i < month; i++) {
totalDays += getNumberOfDays(year, i);
}
return totalDays;
}
public static void printMonthBody(int year, int month){
int startDay = getStartDay(year, month);
int numberOfDaysInMonth = getNumberOfDays(year, month);
for (int i = 0; i < startDay; i++) {
System.out.print(" ");
}
for (int j = 1; j <= numberOfDaysInMonth; j++) {
System.out.printf("%4d", j);
if (0 == (j + startDay) % 7) {
System.out.print("\n");
}
}
System.out.print("\n");
}
public static String getMonthName(int month) {
String monthName = "";
switch (month) {
case 1: monthName = "Jan";break;
case 2: monthName = "Feb";break;
case 3: monthName = "Mar";break;
case 4: monthName = "Apr";break;
case 5: monthName = "May";break;
case 6: monthName = "Jun";break;
case 7: monthName = "Jul";break;
case 8: monthName = "Aug";break;
case 9: monthName = "Sep";break;
case 10: monthName = "Oct";break;
case 11: monthName = "Nov";break;
case 12: monthName = "Dec";break;
default: break;
}
return monthName;
}
public static void printMonthTitle(int year, int month) {
System.out.println(" " + getMonthName(month) + " " + year);
System.out.println("----------------------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
public static void printMonth(int year, int month) {
printMonthTitle(year, month);
printMonthBody(year, month);
}
}
打印日历的方法