用Calendar、Date类实现当前月份日历的显示
import java.util.Calendar;
import java.util.Date;
public class CalendarDemo{
public static void main(String[] args){
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());//set date at current date
int year = cal.get(Calendar.YEAR);//get year
int month = cal.get(Calendar.MONTH)+1;//get month,because the return value of cal.get()
//is between 0-11,so the real month needs to add 1
//get how many days in current month
int daysOfMonth = cal.getActualMaximum(cal.DAY_OF_MONTH);
cal.set(cal.DAY_OF_MONTH,1); //set date to the first day of current month
int index = cal.get(cal.DAY_OF_WEEK)-1; //sign how many blanks befor the first day
String[] title = {"Sun","Mon", "Tues","Wed", "Thur", "Fri", "Sat"};//the us custom
int day = 1; //the first day's number
int[][] daysArray = new int[6][7]; //store the days of month
int mark = 0; //sign blanks
//fill the days into daysArray
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
if( mark < index){
daysArray[i][j] = 0;
mark++;
}else{
daysArray[i][j] = day;
day++;
}
if(day > daysOfMonth){
break;
}
}
}
//present the day of month
System.out.println("Year "+ year +" Month " + month);
System.out.println("------------------------------------------------------");
for(String s : title){
System.out.print(s + "\t");
}
System.out.println();
mark = 0;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7;j++){
if(mark <daysOfMonth && daysArray[i][j] == 0){
System.out.print(" " + "\t");
}else if(mark < daysOfMonth && daysArray[i][j] != 0){
System.out.print(daysArray[i][j] +"\t");
mark++;
}else{
break;
}
}
System.out.println();
}
}
}
运行结果如下图: