首页 > 代码库 > 第四章:显示当月日期的小程序。

第四章:显示当月日期的小程序。

 1 package cha4; 2  3 import java.text.DateFormatSymbols; 4 import java.util.Calendar; 5 import java.util.GregorianCalendar; 6  7 public class CalendarTest { 8  9     public static void main(String[] args) {10         GregorianCalendar today = new GregorianCalendar(2014,10,30) ;11         12         int curMonth = today.get(Calendar.MONTH) ;13         today.set(Calendar.DAY_OF_MONTH, 1);14         15         int weekday = today.getFirstDayOfWeek() ;//一个星期的星期几为第一天16         int curWeekday = today.get(Calendar.DAY_OF_WEEK) ;//今天为这个星期的第几天17         int indent = 0 ; //缩进,显示上个月的日期18         19         while(weekday != curWeekday) {20             today.add(Calendar.DAY_OF_MONTH, -1);21             curWeekday = today.get(Calendar.DAY_OF_WEEK) ;22             indent++ ;23         }24         25         String[] weekdayNames = new DateFormatSymbols().getShortWeekdays() ; 26         27         for (String weekdayName : weekdayNames) {28             if(!"".equals(weekdayName.trim()))29                 System.out.print(weekdayName + "\t");30         }31         32         System.out.println();33         34         for(int i =  0 ; i< indent ;i++) {//打印上个月的几天35             System.out.print(today.get(Calendar.DAY_OF_MONTH) + "\t\t");36             today.add(Calendar.DAY_OF_MONTH, 1);37         }38         39         do{40             int day = today.get(Calendar.DAY_OF_MONTH) ;41             System.out.print(day + "\t\t");42             today.add(Calendar.DAY_OF_MONTH, 1) ;43             curWeekday = today.get(Calendar.DAY_OF_WEEK) ;44             if(curWeekday == weekday)45                 System.out.println();46         }while(today.get(Calendar.MONTH) == curMonth) ;47         48     }49 }

 

第四章:显示当月日期的小程序。