主要使用的类为LocalDate,相关API包括:
LocalDate.getMonthValue() //获取月份数字
LocalDate.getDayOfMonth() //获取该月份内的具体日期数字
LocalDate.getDayOfWeek() //获取对应的星期几的字符串
LocalDate.plusDays() //增减相应的天数,返回一个新的LocalDate对象
具体代码:
import java.time.LocalDate;
public class Main {
public static void main(String[] args){
LocalDate localDate = LocalDate.now();
datePrint(localDate);
}
public static void datePrint(LocalDate localDate){
System.out.println("MON TUE WED THU FRI SAT SUN");
int month = localDate.getMonthValue();//当前月份
int today = localDate.getDayOfMonth();//当前日期
int value = localDate.plusDays(-(today-1)).getDayOfWeek().getValue();//当前星期几
LocalDate date = localDate.plusDays(-(today-1));
for(int i=1;i<value;i++){
System.out.print(" ");
}
while(date.getMonthValue()==month){
int day = date.getDayOfMonth();
if(date.getDayOfWeek().getValue()==1 && date.getDayOfMonth()!=1) System.out.println();
if(date.getDayOfMonth()<10&&day!=today){
System.out.print(" ");
}else if(date.getDayOfMonth()<10&&day==today){
System.out.print(" *");
}else if(date.getDayOfMonth()>=10&&day!=today){
System.out.print(" ");
}else{
System.out.print("*");
}
System.out.print(date.getDayOfMonth()+" ");
date = date.plusDays(1);
}
}
}
运行结果: