I am trying to figure out how to make my program count the number of Sundays in a week.
I have tried the following thing:
if (date.DAY_OF_WEEK == date.SU
Calendar cal = ...;
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("Sunday!");
}
Calendar.DAY_OF_WEEK
always equals to 7
no matter what instance of Calendar
you are using (see this link), it is a constant created to be used with the Calendar.get()
method to retrieve the correct value.
It is the call to Calendar.get(Calendar.DAY_OF_WEEK)
that will return the real day of week. Besides, you will find useful values in the Calendar
class like Calendar.SUNDAY
(and the other days and months) in order for you to be more explicit in your code and avoid errors like JANUARY
being equal to 0
.
Edit
Like I said, the Calendar
class does contains useful constants for you to use. There is no month number 12
they start at 0
(see above), so DECEMBER
is month number 11
in the Java Date handling.
Calendar startDate = Calendar.getInstance();
startDate.set(2012, Calendar.DECEMBER, 02);
if (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("true");
} else {
System.out.println("FALSE");
}
Will print true
of course.