实现效果如图:
实现代码:
package programlist;
import java.time.DayOfWeek;
import java.time.LocalDate;
/**
* @BelongsProject: JavaCore
* @BelongsPackage: programlist
* @Classname: CalendarTest4_1
* @Author: admin
* @Date: 2022/6/24 15:50
* @Description:
*/
public class CalendarTest4_1 {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
//获得当前的月、日
int month = date.getMonthValue();
int today = date.getDayOfMonth();
date = date.minusDays(today - 1);//将date设置为这个月第一天
DayOfWeek weekday = date.getDayOfWeek();//得到这一天(这个月第一天)是星期几
int value = weekday.getValue();//1=Monday,...,7=Sunday
//打印日历的主体
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();
}
}
}