Code To Find Number of Sunday for the given Month

Suppose we know the month and year and we want to calculate the number of sunday in that month.

Here is the code:
private string GetNumberOfSundays(Int32 Month, Int32 Year)
{
DateTime StartDate = Convert.ToDateTime(Month.ToString() + "/01/" + Year.ToString());
Int32 iDays = DateTime.DaysInMonth(Year,Month);
DateTime EndDate = StartDate.AddDays(iDays - 1);
Int32 Count = 0;
Int32 SundayCount = 0;
while (StartDate.DayOfWeek != DayOfWeek.Sunday)
{
StartDate = StartDate.AddDays(1);
}
SundayCount = 1;
StartDate = StartDate.AddDays(7);
while (StartDate <= EndDate) { SundayCount += 1; StartDate = StartDate.AddDays(7); } return SundayCount.ToString(); }


Pass the Month and Year as Integer value and the above method will return the number of sunday in that month as a string value.

0 comments: