Logan Mzz Logan Mzz - 5 months ago 31
Java Question

Java Calendar - First day of week VS actual minimum

I was testing a piece of our date management framework which is supposed to reset some Calendar fields (using actual minimum).

However, when changing first day of week, Calendar always return SUNDAY (

1
) as actual minimum for day of weeks. Is it a bug ?

MVCE:



import java.util.*;

public class Main {
public static void main(String[] args) {
System.out.printf("Java specification: %s%n", System.getProperty("java.vm.specification.version"));
System.out.printf("Java version: %s%n", System.getProperty("java.specification.version"));
System.out.printf("VM version: %s%n", System.getProperty("java.vm.version"));

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

int[] days = { 1, 5, 7 };
for (int day : days) {
cal.setTimeInMillis(0L);
cal.setFirstDayOfWeek(day);
System.out.printf("expected: %d, actual: %d%n", day, cal.getActualMinimum(Calendar.DAY_OF_WEEK));
}
}
}



Answer

You should use cal.getFirstDayOfWeek() instand of cal.getActualMinimum(Calendar.DAY_OF_WEEK)

because cal.getActualMinimum(Calendar.DAY_OF_WEEK) will always return sunday look at the implementation of the getActualMinimum(Calendar.DAY_OF_WEEK) in java source code

  public int getActualMinimum(int field) {
        if (field == DAY_OF_MONTH) {
            GregorianCalendar gc = getNormalizedCalendar();
            int year = gc.cdate.getNormalizedYear();
            if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) {
                long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate));
                BaseCalendar.Date d = getCalendarDate(month1);
                return d.getDayOfMonth();
            }
        }
        return getMinimum(field);
    }

And getMinimum is :-

   public int getMinimum(int field) {
        return MIN_VALUES[field];
    }

and MIN_VALUES array is defined as :-

 static final int MIN_VALUES[] = {
        BCE,            // ERA
        1,              // YEAR
        JANUARY,        // MONTH
        1,              // WEEK_OF_YEAR
        0,              // WEEK_OF_MONTH
        1,              // DAY_OF_MONTH
        1,              // DAY_OF_YEAR
        SUNDAY,         // DAY_OF_WEEK
        1,              // DAY_OF_WEEK_IN_MONTH
        AM,             // AM_PM
        0,              // HOUR
        0,              // HOUR_OF_DAY
        0,              // MINUTE
        0,              // SECOND
        0,              // MILLISECOND
        -13*ONE_HOUR,   // ZONE_OFFSET (UNIX compatibility)
        0               // DST_OFFSET
    };
Comments