控制台打印日历demo

  • Post author:
  • Post category:其他


 
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;
    }

}
 



版权声明:本文为weixin_39556804原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。