public static void main(String[] args) throws IOException {
//初始化日历对象
Calendar calendar = Calendar.getInstance();
//当前日期
int today = calendar.get(Calendar.DAY_OF_MONTH);
//当前月份
int month = calendar.get(Calendar.MONTH);
//设置日历为当前月第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
//获取当前月第一天在当前周的位置
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
//获取当前月第一天所在周的第一天
int firstDayOfWeek = calendar.getFirstDayOfWeek();
//首行缩进天数
int day = 0;
//如果日历当前日期不是所在周的第一天,则循环查找
while(weekDay != firstDayOfWeek){
//缩进天数自加
day++;
//日历当前天数向前减一,例如7月1日,执行之后为6月30日
calendar.add(Calendar.DAY_OF_MONTH, -1);
//获取日历当前日期在一周中的第几天
weekDay = calendar.get(Calendar.DAY_OF_WEEK);
}
//获取周天数简称,如星期一,mon等
//根据地区不同显示不同,可以通过Locale.setDefault(Locale.CANADA);设置
String[] arys = new DateFormatSymbols().getShortWeekdays();
//循环打印周天数简称
do{
System.out.print("\t"+arys[weekDay]);
calendar.add(Calendar.DAY_OF_MONTH, 1);
weekDay = calendar.get(Calendar.DAY_OF_WEEK);
}while(weekDay != firstDayOfWeek);
System.out.println();
//根据当前月第一天在周中的天数设置首行缩进
for(int i = 1; i <= day; i++){
System.out.print("\t");
}
//设置日历对象时间为当前月第一天,准备打印日历
calendar.set(Calendar.DAY_OF_MONTH, 1);
//循环打印日期
do{
int now = calendar.get(Calendar.DAY_OF_MONTH);
System.out.print("\t"+now);
//标记出当前日期
if(today == now){
System.out.print("*");
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
weekDay = calendar.get(Calendar.DAY_OF_WEEK);
//如果处理后的日期是所在周的第一天,则换行
if(weekDay == firstDayOfWeek){
System.out.println();
}
}while(calendar.get(Calendar.MONTH) == month);
}