1. 程式人生 > >控制檯列印日曆demo

控制檯列印日曆demo

public class Calendar {
    public static void main(String[] args) {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int year = calendar.get(java.util.Calendar.YEAR);
        System.out.println(year);
        print(year, 9);
    }

    private static void print(int year, int month) {
        int[] months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 31, 30 };
        int yearDays; //當年以前的總天數
        int monthDays = 0; //月天數
        int allDays; //總天數
        int sum; //星期數
        int firstWeek; //本月第一天星期幾
        int theMonth; //當月的天數

        yearDays = calcYear(year);
        if (runnian(year)) {
            months[1] = 29;
        }
        for (int i = 0; i < month - 1; i++) {
            monthDays += months[i];
        }
        allDays = monthDays + yearDays; //獲得包括今年到本月份之前的全部總天數
        sum = allDays % 7;
        if (sum > 7) {
            sum = sum % 7;
        }
        firstWeek = sum + 1;
        if (firstWeek > 7) {
            firstWeek = firstWeek % 7; //本月的第一天星期數
        }
        theMonth = months[month - 1];
        System.out.println("  日  一  二  三  四  五  六 ");
        for (int i = 0; i < firstWeek; i++) {
            System.out.print(" \t");
        }
        for (int i = 1; i <= theMonth + 1; i++) {
            System.out.printf("%4d", i);
            if ((i + firstWeek) % 7 == 0) {
                System.out.println();
            }
        }
    }

    //獲取年的總天數
    private static int calcYear(int year) {
        int yearTotal = 0;
        for (int i = 1900; i < year; i++) {
            if (runnian(i)) {
                yearTotal = yearTotal + 366;
            } else {
                yearTotal = yearTotal + 365;
            }
        }
        return yearTotal;
    }

    //閏年
    private static boolean runnian(int year) {
        boolean bool = false;
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            bool = true;
        }
        return bool;
    }

}