在java控制檯列印日曆
阿新 • • 發佈:2018-12-25
public static void main(String[] args) { Locale.setDefault(Locale.ENGLISH); GregorianCalendar d = new GregorianCalendar(); //現在是當前月份的第幾天 int today = d.get(Calendar.DAY_OF_MONTH); //現在是幾月份 int month = d.get(Calendar.MONTH); //設定當前時間為這個月的第一天 d.set(Calendar.DAY_OF_MONTH, 1); //月份第一天是星期幾 int weekday = d.get(Calendar.DAY_OF_WEEK); //獲取一星期的第一天 int firstDayOfWeek = d.getFirstDayOfWeek(); int indent = 0; //如果月份的第一個天不是一個星期的第一天,要知道空幾個空格,並把當前時間設定到一星期的第一天 while (weekday != firstDayOfWeek) { indent++; d.add(Calendar.DAY_OF_MONTH, -1); weekday = d.get(Calendar.DAY_OF_WEEK); } //列印星期頭 String[] weekdayNames = new DateFormatSymbols().getShortWeekdays(); do { System.out.printf("%4s", weekdayNames[weekday]); d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); } while (weekday != firstDayOfWeek); System.out.println(); for (int i = 1; i <= indent; i++) { System.out.print(" "); } //設定當前時間為月初 d.set(Calendar.DAY_OF_MONTH, 1); do { //列印天數 int day = d.get(Calendar.DAY_OF_MONTH); System.out.printf("%3d", day); //標準當前日期 if (day == today) { System.out.print("*"); } else { System.out.print(" "); } d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); //到日期第一天,換行 if (weekday == firstDayOfWeek){ System.out.println(); } } while (d.get(Calendar.MONTH) == month); //最後是否需要換行 if (weekday != firstDayOfWeek){ System.out.println(); } }