直接看例子:
import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; public class CalendarTest { public static void main(String[] args) { GregorianCalendar d = new GregorianCalendar(); String[] weekdayNames = new DateFormatSymbols(Locale.US).getShortWeekdays(); String[] monthsNames = new DateFormatSymbols(Locale.US).getShortMonths(); int today = d.get(Calendar.DAY_OF_MONTH); System.out.printf("Today is %2d in the month.%n", today); int month = d.get(Calendar.MONTH); System.out.printf("This month is %4s.%n", monthsNames[month]); d.set(Calendar.DAY_OF_MONTH, 1); System.out.printf("The first day of this month is %d.%n", d.get(Calendar.DAY_OF_MONTH)); int weekday = d.get(Calendar.DAY_OF_WEEK); System.out.printf("The first week day of this month is %4s.%n", weekdayNames[weekday]); int firstDayOfWeek = d.getFirstDayOfWeek(); System.out.printf("The first week day of this week is %4s.%n", weekdayNames[firstDayOfWeek]); int indent = 0; while (weekday != firstDayOfWeek) { indent++; // 当月开始日期减1天,星期自然也就减1天,一直减到星期天 d.add(Calendar.DAY_OF_MONTH, -1); weekday = d.get(Calendar.DAY_OF_WEEK); } System.out.printf("Today - Monday = %d.%nThe day is %4s now.%n", indent, weekdayNames[weekday]); System.out.printf("The day is %4s %4s now.%n", monthsNames[d.get(Calendar.MONTH)], d.get(Calendar.DAY_OF_MONTH)); System.out.println(""); // 打印星期名称,这里采用美式日期格式,从周日开始 do { // 从下标为1开始取,美式星期下标为1取到的是周日 System.out.printf("%4s", weekdayNames[weekday]); // 上面日期已经减到星期天了,所以现在又从星期天开始加回去,下标从1开始加到7再变回1 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.printf("%4s", ""); } 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(" "); } // 日期加1,直到月末 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(); } } }
输出:
Today is 23 in the month. This month is Aug. The first day of this month is 1. The first week day of this month is Wed. The first week day of this week is Sun. Today - Monday = 3. The day is Sun now. The day is Jul 29 now. Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23* 24 25 26 27 28 29 30 31