venerdì 5 luglio 2013

Java Calendar

In this post i show how to obtain the calendar of the current month, and how to know the days of the week.
First of all you need to obtain three parameters, number of days of the current month, the month and the year.

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
int numDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);

To know which day of the week the date belongs:

for (int date = 1; date <= numDays; date++) {
   cal.set(year, month, date);
   String dayName = dayName(cal.get(Calendar.DAY_OF_WEEK));
   System.out.println(date + "-" + month + "-" + year + " " + dayName);    
}

String dayName(int day) {
   switch (day) {
      case Calendar.MONDAY:   return "Monday";
      case Calendar.TUESDAY:  return "Tuesday";
      case Calendar.WEDNESDAY:return "Wednesday";
      case Calendar.THURSDAY: return "Thursday";
      case Calendar.FRIDAY:   return "Friday";
      case Calendar.SATURDAY: return "Saturday";
      case Calendar.SUNDAY:   return "Sunday";
      default:                return "";
   }
}

Output:

1-6-2013 Monday
2-6-2013 Tuesday
3-6-2013 Wednesday
4-6-2013 Thursday
5-6-2013 Friday
6-6-2013 Saturday
7-6-2013 Sunday
8-6-2013 Monday
9-6-2013 Tuesday
10-6-2013 Wednesday
.......