java實現一個月的日曆列印

Pop_Rain發表於2017-06-21


import java.text.DateFormatSymbols;
import java.util.*;

public class Test
{
   public static void main(String[] args)
   {
      // construct d as current date
	  Locale.setDefault(Locale.ENGLISH);
	   
      GregorianCalendar d = new GregorianCalendar();
      
      int month = d.get(Calendar.MONTH); //用於迴圈列印當前月份的月曆__月份判斷
      int today = d.get(Calendar.DAY_OF_MONTH); //用於給當前日期後面加"*"
      
      String weekdays[] = new DateFormatSymbols().getShortWeekdays(); //儲存7個星期名
   
      for(int i=1; i<8; ++i)
    	  System.out.print(weekdays[i]+" ");	//列印月曆頭部,7個星期名
      System.out.println();
      
      d.set(Calendar.DAY_OF_MONTH, 1); //設定d的日期為當月1號
      int weeknameofFirstday = d.get(Calendar.DAY_OF_WEEK);//獲得當月1號的星期名
      
      int cnt = 1;
      while(weekdays[cnt] != weekdays[weeknameofFirstday])  //列印日曆第一行,判斷當月1號從第一行的哪裡開始列印
      {
    	  System.out.print("    ");
    	  ++cnt;
      }
      
      do
      {
    	  int day = d.get(Calendar.DAY_OF_MONTH);
    	  System.out.printf("%3s", day);
    	  if(day == today)
    		  System.out.print("*");
    	  else
    		  System.out.print(" ");
    	  
    	  if(weekdays[d.get(Calendar.DAY_OF_WEEK)] == weekdays[7]) //判斷是否需要換行列印
    		  System.out.println();
    	  d.add(Calendar.DAY_OF_MONTH, 1);
      }while(d.get(Calendar.MONTH) == month);
   }
}

結果列印效果:



相關文章