+ Start a Discussion
Narendra Reddy GopavaramNarendra Reddy Gopavaram 

How to calculate number of sunday's in a given month and year?

Hi All,

Can any one help me to calculate number of sunday's in a given month and year using apex and vf page.

Ex: If i select March 2017 from vf page, i need to calculate number of sunday's from selected month and year.

Thanks in advance.
Best Answer chosen by Narendra Reddy Gopavaram
Andrew GAndrew G
Investigate the dayOfWeek method
 
Integer month = 10;  
Integer year = 2019;
Integer numberDays = Date.daysInMonth(year, month);
Integer noOfSun = 0;

for(Integer i=1;i<=numberDays ;i++)
{
    Date myDate = date.newInstance(year, month, i);
    Datetime dt = (DateTime)myDate;
    if(dt.format('EEEE' == 'Sunday')
    {
        noOfSun = noOfSun + 1;  
    }
}

Save the computations related to start date and modulos.

Regards
Andrew

All Answers

Maharajan CMaharajan C
Hi narendra,

Please refer the below code:


Integer month = 10;  
Integer year = 2019;

Integer numberDays = Date.daysInMonth(year, month);
Date startDate = date.newInstance(2001, 1, 1);
List<String> listDay = new List<String>{'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday','Saturday' , 'Sunday' };

system.debug( ' ==> ' + numberDays );
Integer noOfSun = 0;
for(Integer i=1;i<=numberDays ;i++)
{
    Date myDate = date.newInstance(year, month, i);
    Integer remainder = Math.mod(startDate.daysBetween(myDate) , 7);
    String dayValue = listDay.get(remainder);
    if(dayValue == 'Sunday')
    {
        noOfSun = noOfSun + 1;  
    }
}

system.debug(  ' @@@ noOfSun =>  ' + noOfSun );


Thanks,
Maharajan.C
Andrew GAndrew G
Investigate the dayOfWeek method
 
Integer month = 10;  
Integer year = 2019;
Integer numberDays = Date.daysInMonth(year, month);
Integer noOfSun = 0;

for(Integer i=1;i<=numberDays ;i++)
{
    Date myDate = date.newInstance(year, month, i);
    Datetime dt = (DateTime)myDate;
    if(dt.format('EEEE' == 'Sunday')
    {
        noOfSun = noOfSun + 1;  
    }
}

Save the computations related to start date and modulos.

Regards
Andrew
This was selected as the best answer
david deodavid deo
I need to be able to count the number of Sundays, Mondays, Tuesdays, etc. between the start and ... 3 points · 2 years ago · edited 2 years ago. 
$total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year); for($i=1 ... return $sundays; ... any other day in a month then set the $day accordingly.
Write a program that gets the number (Day date) of the day in that month and prints ... Returns: 0=Sunday, 1=Monday, etc unsigned day_of_week( unsigned year, ... We won't concern ourselves with days of any other month. 2.
https://customersurveyinfo.com