Displaced Hoser Displaced Hoser - 3 months ago 12
Java Question

DAY_OF_WEEK always returns 7 in Java GregorianCalendar

So I want to do something with Java GregorianCalendar that seems to be going way harder than it should. I want to get the day of the week from the month and date. But it won't do that. I know that people often get the wrong answer to this because they don't know month is numbered from 0 while DAY_OF_WEEK is numbered from 1 (like here and here). But that's not my problem. My problem is that DAY_OF_WEEK always, always, returns 7, no matter what I set the date to. When I convert the GregorianCalendar to string, DAY_OF_WEEK appears as ?, even though I have set year, month, and dayOfMonth.

The code where this is happening:

GregorianCalendar theDate;

public ObservableDate(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
{
theDate = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
theDate.setFirstDayOfWeek(GregorianCalendar.SUNDAY);
System.out.println("DAY_OF_WEEK = "+theDate.DAY_OF_WEEK);
System.out.println(theDate.toString());
}


The code that calls it:

ObservableDate theDate = new ObservableDate(2001, 3, 24, 9, 00, 00);


Output:

DAY_OF_WEEK = 7
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2001,MONTH=3,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=24,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]


Any idea why this is happening?

Answer

You are accessing the field constant instead of getting its' value. I believe you wanted to use something like,

System.out.println("DAY_OF_WEEK = " + theDate.get(Calendar.DAY_OF_WEEK));