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.

Thanks

Lakhan Pal Garg

Author: Michael HansenCompany URL: http://www.dotnetspark.comPosted Date: April 04, 2012

The number of Saturdays or Sundays will always be 4 or 5. After much gnashing of teeth, here is the single formula that gives you the answer.

iif(Today.AddDays(-Today.Day).Subtract(Today.AddDays(-Today.Day).AddMonths(-1).AddDays(4-Today.AddDays(-Today.Day).AddMonths(-1).DayOfWeek)).TotalDays/7 > 4,5,4)

1. Today.AddDays(-Today.Day) gives you the last day of the previous month.

2. Today.AddDays(-Today.Day).AddMonths(-1) gives you the last day of the month before that.

3. AddDays(4-Today.AddDays(-Today.Day).AddMonths(-1).DayOfWeek)) in this case I'm looking for the first thursday of the month so I subtract the last day of the previous month's day of the week from 4. If we were looking for the first sunday I would subtract last day of the previous month from 7. In any case, I end up with the first Monday-Sunday of the month.

4. Subtract is a timespan function that gives me the time elapsed between the two dates. The TotalDays method converts this time span to days.

5. Dividing the total days elapsed between the first ___day and 7 gives me the number of weeks between the two dates. If that number is greater than 4 then I know I started a 5th week beginning on that day. You could just divide by 28 and if the number is greater than 1 then there are 5 weeks, otherwise there are 4 weeks.