• Register
Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

How can I find Sundays of current month and how to get count of Sundays in java?

0 votes
18 views
How can I find Sundays of current month and how to get count of Sundays in java?
asked Dec 6, 2017 in Java by Pavan rajput

1 Answer

0 votes
See the following example to get all Sundays and its count.

import java.util.Calendar;

public class Sundays {
    public static void main(String[] args) {
        System.out.println("Sunday Dates of Current Month:");
    //get calendar object
        Calendar cal = Calendar.getInstance();
    //set current month date form starting
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        int month = cal.get(Calendar.MONTH);
        int countSunday = 0;
        do {
            int day = cal.get(Calendar.DAY_OF_WEEK);
            if (day == Calendar.SUNDAY) {
                countSunday++;
                System.out.println(cal.get(Calendar.DAY_OF_MONTH));
            }
            cal.add(Calendar.DAY_OF_WEEK, 1);
        }  while (cal.get(Calendar.MONTH) == month);
        
        System.out.println("Total Sunday: "+countSunday);
    }
}

Output:-
Sunday Dates of Current Month:
3
10
17
24
31
Total Sunday: 5
answered Dec 6, 2017 by ranju_12 (1,740 points)
...