0

Sorry for asking daft question but I cannot get correct number of weeks in June 2014 returned by Calendar:

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MONTH, Calendar.JUNE);
    calendar.set(Calendar.YEAR, 2014);
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    System.out
        .println("first day of week: " + calendar.getFirstDayOfWeek());
    System.out.println("weeks in month: "
        + calendar.getActualMaximum(Calendar.WEEK_OF_MONTH));
    System.out.println("days in month: "
        + calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}

I am getting:

first day of week: 2
weeks in month: 5
days in month: 30

enter image description here

Why number of weeks in June 2014 is not 6? I am using jdk1.8.0_05 on Mac OS X 10.9.3.

ruruskyi
  • 2,018
  • 2
  • 26
  • 37

1 Answers1

7

The definition of a week depends on what each Locale (country, region, whatever) defines as the first day of the week. You can check that with Calendar#getFirstDayOfWeek(). It also depends on what it considers the minimal days in the first week should be. You can get that with Calendar#getMinimalDaysInFirstWeek(). Your Locale seems to show that it needs more than one day to consider that period a week.

For example, with Locale.CANADA, I get 6 weeks since the getMinimalDaysInFirstWeek() returns 1.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724