I want to get the ISO Day of the Week using the Calendar
API, but it returns the wrong day number.
Sunday is the last day of the week and should be number 7 from the ISO standard, with Monday being the first day as number 1.
But running the following code for a Sunday (2017-07-30) is returning me number 1. Why is Calendar
API returning me a different value?
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, Calendar.JULY);
cal.set(Calendar.DAY_OF_MONTH, 30);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
The result is: 1
I tried using Joda Time and it worked fine, but I need to do it using Calendar and Java 6, so using another library is not a solution.
The int constants start with Sunday and end with Saturday.
Documented in java.util.Calendar
JavaDoc for Java 6.
So my proposal is to calculate it on your own.