根据输入的日期展示当前月份的日历
程序员文章站
2022-05-07 21:55:58
...
//根据具体日期展示当前月份的日历
public static void setCalendar(){
//输入日期并将日期转化
System.out.print("请输入一个日期,如2017-12-09");
Scanner scanner=new Scanner(System.in);
String inputDate=scanner.next();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try {
date=dateFormat.parse(inputDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.print("您输入的日期是:"+dateFormat.format(date)+"\n");
//输出日历
System.out.print("\t日\t一\t二\t三\t四\t五\t六\n");
Calendar calendar=Calendar.getInstance();
//将date转换为calendar
calendar.setTime(date);
int thisDay=calendar.get(Calendar.DATE);
int maxDay=calendar.getActualMaximum(Calendar.DATE);
//判断当月第一天为星期几
calendar.set(Calendar.DATE,1);
int first=calendar.get(Calendar.DAY_OF_WEEK);
StringBuffer stringBuffer=new StringBuffer();
//在第一天前加入空格
if (first!=1){
for (int i = 0; i < first-1; i++) {
stringBuffer.append("\t");
}
}
for (int i=1;i<=maxDay;i++){
calendar.set(Calendar.DATE,i);
DecimalFormat decimalFormat=new DecimalFormat("00");
String s=decimalFormat.format(i);
if (i==thisDay){
s="*"+i;
}
stringBuffer.append( "\t" + s);
if (calendar.get(Calendar.DAY_OF_WEEK)==7){
stringBuffer.append("\n");
}
}
System.out.print(stringBuffer);
}