faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 3 of 5 people (60%) answered Yes

Entry

How can I create a calendar that goes to the 4th Thursday in April of the current year?

Oct 27th, 2004 23:24
Tom McGuire, Tiffany C.,


You can compute the Date of the 4th Thursday in April of the current 
year using the following code:

   Calendar cal = Calendar.getInstance();
   cal.set(Calendar.MONTH,Calendar.APRIL);
   cal.set(Calendar.DAY_OF_MONTH,1);
   int maxDayOfMonth=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
   int currentDayOfMonth=1;
   while(currentDayOfMonth<=maxDayOfMonth){
      if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.THURSDAY){
         cal.set(Calendar.DAY_OF_MONTH,
            currentDayOfMonth+3*cal.getMaximum(Calendar.DAY_OF_WEEK));
         break;
      }
      cal.set(Calendar.DAY_OF_MONTH,++currentDayOfMonth);
   }
   System.out.println(cal.getTime());

This approach finds the first instance of a Thursday in the given month 
(current year is assumed) and advances 3 weeks using the current 
calendar (could be Gregorian, could be some other calendar based on 
locale; I suppose you could just add 21 days and be done with it...)

I would be interested to know why this is an important question...