.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Code To Find Number of Sunday for the given Month

Posted By:Lakhan Pal Garg       Posted Date: May 09, 2010    Points: 10    Category: Visual Studio    URL: http://www.dotnetspark.com  

To get the number of sundays for given month & Year.

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.


Lakhan Pal Garg


Further Readings:

Author: Michael Hansen         Company URL: http://www.dotnetspark.com
Posted 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.

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend