现在的位置: 首页 > 综合 > 正文

《java核心技术》实例—GregorianCalendar

2013年12月03日 ⁄ 综合 ⁄ 共 1441字 ⁄ 字号 评论关闭

import java.util.*;
import java.text.DateFormatSymbols;
public class CalendarTest {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
GregorianCalendar d=new GregorianCalendar();   //create a GregorianCalendar object

int day=d.get(Calendar.DAY_OF_MONTH);
int month=d.get(Calendar.MONTH);               //get the day_of_month and month in the boject

int firstday=d.getFirstDayOfWeek();            //get the first day of week 

//calculate the indent in the first line
d.set(Calendar.DAY_OF_MONTH, 1);              //set the 'd' as the first day in the month
int weekday=d.get(Calendar.DAY_OF_WEEK);

int indent=0;    
while(weekday!=firstday)      
{
indent++;
d.add(Calendar.DAY_OF_MONTH, -1);
weekday=d.get(Calendar.DAY_OF_WEEK);
}

//print out the signal of week 
String [] weekdayNames=new DateFormatSymbols().getShortWeekdays();

do
{
System.out.printf("%4s",weekdayNames[weekday]);
d.add(Calendar.DAY_OF_MONTH, 1);
weekday=d.get(Calendar.DAY_OF_WEEK);
}while(weekday!=firstday);

//print out the calendar formally
//add '*' if needed
System.out.println();  
for(int i=1;i<=indent;i++)
{
System.out.println("    ");    //print out the indent in the first line
}

d.set(Calendar.DAY_OF_MONTH, 1);
do
{
int s=d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d",s);

   if(s==day)
   {
    System.out.print("*");
   }
   else
   {
    System.out.print(" ");
   }
   
   d.add(Calendar.DAY_OF_MONTH,1);
   weekday=d.get(Calendar.DAY_OF_WEEK);
   
   if(weekday==firstday)
   {
    System.out.println();
   }
}while(d.get(Calendar.MONTH)==month);

if(weekday!=firstday)
{
System.out.println();
}

}

}

抱歉!评论已关闭.