Check if the Calendar date is a sunday
calendar, date, java
Solution
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.
Problem
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.SUNDAY) { System.out.println("Sunday!"); } ``` Yet it does not seem to work? When I try to `System.out.Println the date.DAY_OF_WEEK` I get: `7` Does anyone know how I can check if the current calendar date is Sunday? UPDATE FOR MORE INFORMATION firt of all the date.DAY_OF_WEEK is a Calendar object! i made sure to set the Calendar object `date` to a sunday The system out print where i get 7 is what it returns to me when i try to run `date.DAY_OF_MONTH` even if the day it set to a sunday 2nd UPDATE TO ALEX This is more or less my code ``` Calendar startDate = Calendar.getInstance(); startDate.set(2012, 12, 02); if (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { System.out.println("true"); }else { System.out.println("FALSE"); } ```