程序关键步骤:
首先构造一个日历对象,并用当前的日期和时间进行初始化
LocalDate date = LocalDate.now();
// 获得当前的月和日
int month = date.getMonthValue();
int today = date.getDayOfMonth();
将date设置为这个月的第一天,并得到这一天为星期几
// set to start of month
date = date.minusDays(today - 1);
DayOfWeek weekday = date.getDayOfWeek();
// 1 = Monday,...,7 = Sunday
int value = weekday.getValue();
变量weekday设置为DayOfWeek类型的对象。我们调用这个对象的getValue防范来得到星期几的一个数值。这会得到一个整数,这里遵循国际惯例,即周末式一周的末尾,星期一就返回1,星期二就返回2,以此类推。星期日返回7.
迭代打印日期值,如果date是当前日期,这个日期用一个*标记。接下来把date推进到下一天。如果到达新一周的第一天,则换行打印:
// 只要date还在当月就要继续迭代
while (date.getMonthValue() == month) {
System.out.printf("%3d", date.getDayOfMonth());
if (date.getDayOfMonth() == today)
System.out.print("*");
else
System.out.print(" ");
// plusDays方法会得到一个新的LocalDate,这个新日期对象则是距离当前对象指定天数的一个新日期
date = date.plusDays(1);
if (date.getDayOfWeek().getValue() == 1)
System.out.println();
}
完成程序代码:
public static void calendarTest() {
// get date of today
LocalDate date = LocalDate.now();
// get month
int month = date.getMonthValue();
// get day
int today = date.getDayOfMonth();
// set to start of month
date = date.minusDays(today - 1);
// get current day of the week
DayOfWeek weekday = date.getDayOfWeek();
int value = weekday.getValue();
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
for (int i=1; i< value; i++) {
System.out.print(" ");
}
while (date.getMonthValue() == month) {
// 输出三位整型数,不够三位的右对齐
System.out.printf("%3d", date.getDayOfMonth());
if (date.getDayOfMonth() == today)
System.out.print("*");
else
System.out.print(" ");
date = date.plusDays(1);
// mon print in newline
if (date.getDayOfWeek().getValue() == 1)
System.out.println();
}
if (date.getDayOfWeek().getValue() != 1)
System.out.println();
}
运行程序:
Mon Tue Wed Thu Fri Sat Sun
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
- int getYear() --- 得到当前的年
- int getMonthValue --- 得到当前的月
- int getDayOfMonth --- 得到当前的日
- DayOfWeek getDayOfWeek --- 得到当前日期是星期几,作为DayOfWeek类的一个实例返回。调用getVlaue来得到1~7之间的一个数,表示星期几
- LocalDate plusDays(int n) --- 生成当前日期之后几天日期
- LocalDate minusDays(int n) --- 生成当前日期之前几天的日期