0

I want to know the number of Sundays in the current month. For example, March 2019 has 5 Sundays, so I want to reach this number. I have tried this code that I found in many places here but doesn't give the result.

Calendar cal = Calendar.getInstance();
    int mes_cal = cal.get(Calendar.MONTH);
    int ano_cal = cal.get(Calendar.YEAR);

    int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        cal.set(ano_cal, mes_cal, 1);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY) {
            count++;
            System.out.println(count);
        }
    }

SOLUTION (from @primo suggested link with only one correction)

Calendar cal = Calendar.getInstance();
    mes_cal = cal.get(Calendar.MONTH);
    ano_cal = cal.get(Calendar.YEAR);

public int countDayOccurence(int year, int month,int dayToFindCount) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == dayToFindCount) {
            count++;
        }
    }
    return count;
}

And then call the method

int countSunday = countDayOccurence(ano_cal,mes_cal,Calendar.SUNDAY);

2 Answers2

0

pass day as 3rd argument in cal.set

Calendar cal = Calendar.getInstance();
int mes_cal = cal.get(Calendar.MONTH);
int ano_cal = cal.get(Calendar.YEAR);

int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
    cal.set(ano_cal, mes_cal, day);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    if (dayOfWeek == Calendar.SUNDAY) 
        count++;
}

System.out.println("Total Sunday : "+count);
Ankit Dubey
  • 1,000
  • 1
  • 8
  • 12
  • Two issues with your answer. First, month has to add 1 because of month begin from 0, Second, it just lists as "1", "2", "3", "4" and I wanted to reach the number 4 that is the total number of sundays in the month. – Jose Borges Mar 30 '19 at 06:28
  • Thank you @JoseBorges, in that case we can use count variable. As it will have the total Sundays value in a month – Ankit Dubey Mar 30 '19 at 06:35
0
function getNumberOFSundayInCurrent() {

var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth();
  var cur_date = new Date(year,month,1);
  var count = 0;
  while (cur_date.getMonth() === month) {
    if(cur_date.toLocaleDateString('en-US',{weekday:'long'}) === 'Sunday')
      count += 1;
    cur_date.setDate(cur_date.getDate() + 1);
  }
  return count;
}

console.log(getNumberOFSundayInCurrent());
Pawan Sah
  • 21
  • 4