Search code examples
javacalendardayofweekjava.util.calendar

Incorrect data returned by Calendar API


In our business requirement we are supposed to find out the first day of the week.

Since the client is European so I used following code to get it.

But, issue is when I run this code I am getting 2 as the answer where as I am expecting 1.

public class Test{
    public static void main(String[] args) {
        TimeZone eu = TimeZone.getTimeZone("Europe/Berlin"); 
        Locale de = Locale.forLanguageTag("de"); 
        int firstDayOfWeek = Calendar.getInstance(eu, de).getFirstDayOfWeek(); 
        System.out.println(firstDayOfWeek);
    }
}

Can some one help me understand this behavior.


Solution

  • Look at the docs:

    Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

    and here:

    public static final int MONDAY 2

    This shows that the return value depends on the locale.

    If we print this:

    System.out.println(firstDayOfWeek == Calendar.MONDAY);
    

    We'll see true. This means that the first day of week is indeed Monday. It's just that you thought Monday is encoded by 1. In fact, Sunday is encoded as 1.