Tag Archives: calendar

getPrevSaturday

Dealing width dates has always been tricky; recently I needed a way to find the first saturday of the previous week since a given date. Here’s a handy method to get the first occurrence of “Saturday”. If sunday is ‘1′ and saturday is ‘7′ and also if you use Calendar (you should use GregorianCalendar), January is ‘0′ and December is ‘11′… i spent half an hour trying to understand why today’s DAY_OF_WEEK was giving me ‘2′ (Tuesday) while I was expecting 6. Looking at the API you get that today’s MONTH is 10. If you say .set(2010,10,29) you’re setting the calendar to november… d’oh.

1
2
3
4
5
6
7
8
9
10
11
 public Calendar getPrevSaturday(Calendar in) {
   Calendar internal = in;
   Calendar prevSat = Calendar.getInstance();
   for(int i = 1; i <= 7; i ++) {
	   internal.add(Calendar.DATE, - 1);
	   if(internal.get(Calendar.DAY_OF_WEEK) == 7) // is it Saturday? then break and assign that date to our prevSat var
		break;
   }
   prevSat.set(internal.get(Calendar.YEAR), internal.get(Calendar.MONTH), internal.get(Calendar.DAY_OF_MONTH));
   return prevSat;
 }

Ok, how do you use it?

1
2
3
4
5
Calendar dataDummy = Calendar.getInstance(); // this is now.
Calendar prevSat = getPrevSaturday(dataDummy);
System.out.println(prevSat);
// if today is 2010 OCTOBER 29
// then the previous Saturday was 2010 OCTOBER 23