Nov 19

You can use the Calendar class to get the day of the week for a particular date. But if you’re after an algorithm to do the same then Zeller’s congruence may be of interest to you.

Zeller’s congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any Julian or Gregorian calendar date.

Here’s an implementation of the Zeller algorithm in Java.


Calendar today = Calendar.getInstance();
int day = today.get(Calendar.DATE);
int month = today.get(Calendar.MONTH) + 1;
int year = today.get(Calendar.YEAR);

if (month < 3) {
    month += 12;
    year -= 1;
}

int k = year % 100;
int j = year / 100;

// 0 = Saturday, 1 = Sunday, ...
int dayOfWeek = ((day + (((month + 1) * 26) / 10) + 
   k + (k / 4) + (j / 4)) + (5 * j)) % 7;

Hope this helps you implement Zeller in Java.

written by objects \\ tags: , , , , ,

Jul 27

The Calendar class can be used to generate a simple calendar display.

private static void showMonth(Calendar cal) {
	int month = cal.get(Calendar.MONTH);
	int firstDayOfWeek = cal.getFirstDayOfWeek();
	
	// Display day names as headers
	
	cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
	for (int i=0; i<7; i++) {
		
		System.out.print(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()));
		System.out.print(" ");
		cal.add(Calendar.DATE, 1);
	}
	System.out.println();
	
	// Display dates in month
	
	cal.set(Calendar.DATE, cal.getMinimum(Calendar.DATE));
	
	// Now display the dates, one week per line
	
	StringBuilder week = new StringBuilder();
	
	while (month==cal.get(Calendar.MONTH)) {
		
		// Display date
		
		week.append(String.format("%3d ", cal.get(Calendar.DATE)));
					
		// Increment date
		
		cal.add(Calendar.DATE, 1);

		// Check if week needs to be printed
		
		if (cal.get(Calendar.MONTH)!=month) {
			
			// end of month
			// just need to output the month
			
			System.out.println(week);
			
		} else if (cal.get(Calendar.DAY_OF_WEEK)==firstDayOfWeek) {
			
			// new week so print out the current week
			// first check if any padding needed
			
			int padding = 28-week.length();
			if (padding>0) {
				
				// pad out start of week
				
				week.insert(0, 
                                    String.format("%"+padding+"s", " "));
			}
			System.out.println(week);
			week.setLength(0);
		}
	}
}

written by objects \\ tags: , ,

Jul 27

You can use the getDisplayName() in the Calendar class to get a localized (according to Locale) string for any of the Calendar fields.

For example to get the day name you can use the following:

Calendar cal = Calendar.getInstance();
String day = cal.getDisplayName(Calendar.DAY_OF_WEEK, 
   Calendar.LONG, Locale.getDefault())

If you’re looking for an algorithm to get the day of the week then try Zeller’s congruence.

written by objects \\ tags: , ,