Snippet: Kalender ausdrucken, Teil 2: von-bis
Die erste Version meines Kalenderprogramms druckte ein Kalender für ein Jahr. In Anwendungen dürfte häufiger vorkommen, dass es ein Start- und Enddatum gibt, das auch über Jahresgrenzen liegt. Das macht dieses Programm:
public static class CalLine
{
public int year;
public int weekOfYear;
public int month = -1; // 0 <= month <= 11
public int[] day = { -1, -1, -1, -1, -1, -1, -1 };
}
public static List calenderOfTheYear( Date start, Date end )
{
Calendar startCal = new GregorianCalendar();
startCal.setTime( start );
Calendar endCal = new GregorianCalendar();
endCal.setTime( end );
return calenderOfTheYear( startCal, endCal );
}
public static List calenderOfTheYear( Calendar start, Calendar end )
{
List lines = new ArrayList();
// Calender instances are mutable, so copy them
Calendar startCal = (Calendar) start.clone();
Calendar endCal = (Calendar) end.clone();
// For start date: first go backwards to the beginning of the month
// then find monday of this week
while ( startCal.get( Calendar.DAY_OF_MONTH ) != 1 )
startCal.add( Calendar.DAY_OF_YEAR, -1 );
while ( startCal.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
startCal.add( Calendar.DAY_OF_YEAR, -1 );
// For end date: go forwards and find end of month
// then find sunday of this week
while ( endCal.get( Calendar.DAY_OF_MONTH ) != startCal.getActualMaximum( Calendar.DAY_OF_MONTH ) )
endCal.add( Calendar.DAY_OF_YEAR, 1 );
while ( endCal.get( Calendar.DAY_OF_WEEK ) != Calendar.SUNDAY )
endCal.add( Calendar.DAY_OF_YEAR, 1 );
endCal.add( Calendar.DAY_OF_YEAR, 1 ); // add 1 to test with < not