function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Niranjan Reddy @ 22Niranjan Reddy @ 22 

How to calculate number of Sundays in apex class when the input is month and year eg: June 2019 had 4 Sundays

Ajay K DubediAjay K Dubedi
Hi Niranjan,

You can use the below code for your requirement. You can pass the value of month and year as a parameter in the method and use it dynamically.
 
public class CountSunday {
    
    public static void getTotalSundayInMonth(){
        Integer numberDays = date.daysInMonth(2019, 2);   // give the vale according to you as parameter in this method and use it dynamically.
        date startdate = Date.newInstance(2019, 2, 1);
        Integer numberOFSunday = 0;  
        system.debug('numberDays-->'+numberDays);
        system.debug('startdate-->'+startdate);
        for(integer i=0; i<numberDays; i++){
            Date dt = startDate + i;  
            DateTime currDate = DateTime.newInstance(dt.year(), dt.month(), dt.day());  
            
            String todayDay = currDate.format('EEEE');
             system.debug('todayDay-->'+todayDay);
            if(todayDay =='Sunday') { 
                numberOFSunday = numberOFSunday + 1;  
            } 
        }
        System.debug('numberOFSunday-->'+numberOFSunday); // number of sundays
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
Niranjan Reddy @ 22Niranjan Reddy @ 22
when u pass value of month  Dynamically i mean integer variable month  where month takes the Integer  value entered by user.
Then  in the line number 4 im getting error Saying the Argument cannot be Null