最近在看java核心技术卷1,里面有一段打印日历的程序段,效果和linux的cal命令效果很像
不太熟悉java关于日期的类库,如果不会获取某一天是这个月的星期几的话,格式不太好控制
public static void printCalendar() {
LocalDate date = LocalDate.now();
// 获得年份
int year = date.getYear();
// 获得这是第几个月
int month = date.getMonthValue();
System.out.printf("\t %s %d\n", date.getMonth(), year);
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
// 获得今天是这个月的第几天
int today = date.getDayOfMonth();
// 跳转回第一天开始遍历
date = date.minusDays(today - 1);
// 获得这个月第一天对应星期几
int value = date.getDayOfWeek().getValue();
// 打印空白
for (int i = 1; i < value; i++) {
System.out.printf("%4c", ' ');
}
// 开始遍历这个月的天数
while (month == date.getMonthValue()) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
int dayOfMonth = date.getDayOfMonth();
// 如果是周一 换行
if (dayOfWeek.getValue() == 1) {
System.out.println();
}
// 特殊标记today
if (dayOfMonth == today) {
System.out.printf("%3d%c", dayOfMonth, '*');
} else {
System.out.printf("%3d ", dayOfMonth);
}
date = date.plusDays(1);
}
}
运行效果
下面是书上的代码,更简洁一些
public static void printCalendar2() {
LocalDate date = LocalDate.now();
int month = date.getMonthValue();
int today = date.getDayOfMonth();
date = date.minusDays(today - 1);
DayOfWeek dayOfWeek = date.getDayOfWeek();
int value = dayOfWeek.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);
if (date.getDayOfWeek().getValue() == 1) System.out.println();
}
if (date.getDayOfWeek().getValue() != 1) System.out.println();
}
效果