JAVA 按年月列印日曆 Calendar的簡單使用
阿新 • • 發佈:2018-12-25
public class CalendarBook {
public static void main(String[] args) throws ParseException {
CalendarBook cb = new CalendarBook();
cb.printWeekTitle();
cb.printCalendar(2015,8);
}
public void printCalendar(int year,int month) throws ParseException{
String monthStr; //格式化月份,因為要轉成yyyyMMdd格式的
if(month<10){
monthStr = "0"+month;
} else{
monthStr = month+""; //數字跟字串拼接轉成字串格式
}
String yearMonthStr = year+monthStr;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar calendarEnd = Calendar.getInstance();
Calendar calendarStart = Calendar.getInstance();
//根據年份和月份得到輸入月份有多少天
int monthDays = getMonthLastDay(year, month);
//月初的date字串
String dateStartStr = yearMonthStr+"01";
//月末的date字串
String dateEndStr = yearMonthStr+monthDays;
Date startDate = sdf.parse(dateStartStr);
Date endDate = sdf.parse(dateEndStr);
calendarStart.setTime(startDate);
calendarEnd.setTime(endDate);
//得到輸入月份有多少周
int weeks = calendarEnd.get(Calendar.WEEK_OF_MONTH);
//得到當月第一天是星期幾,這裡週日為第一天,從1開始,週一則為2
int dayOfWeek = calendarStart.get(Calendar.DAY_OF_WEEK);
int day = 1;
//當月的第一週做特殊處理,單獨列印一行
for(int i=1;i<=7;i++){
if(i>=dayOfWeek){
System.out.print(" "+day+" ");
day++;
} else{
System.out.print(" ");
}
}
System.out.println();
//開始列印從第二週開始的日期
for(int week=1;week<weeks;week++){
for(int i=1;i<=7;i++){
if(day>monthDays){
break;
}
if(day<10){
System.out.print(" "+day+" ");
} else{
System.out.print(day+" ");
}
day++;
}
System.out.println();
}
}
public int getMonthLastDay(int year,int month){
int monthDay;
int[][] day = {{0,31,28,31,30,31,30,31,31,30,31,30,31},
{0,31,29,31,30,31,30,31,31,30,31,30,31}};
if(year%4==0 && year%100!=0 || year%400==0){
//閏年
monthDay = day[1][month];
} else{
monthDay = day[0][month];
}
return monthDay;
}
public void printWeekTitle(){
System.out.println("日"+" "+"一"+" "+"二"+" "+"三"+" "+"四"+" "+"五"+" "+"六");
}
}
執行結果截圖(執行效果,字型大小5號最佳):