Check if the Calendar date is a sunday

前端 未结 3 764
青春惊慌失措
青春惊慌失措 2021-02-14 00:44

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         


        
3条回答
  •  野的像风
    2021-02-14 01:39

    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.

提交回复
热议问题