Windows Phone Developers

Saturday, May 14, 2011

How to get number of Sundays/Saturdays in a given month using (C#/VB.NET)

Retrieve No of Fridays for the Current Month.

If you come across a situation where you need to know the number of Fridays/Sundays etc for a given month you can use the following snippet.

private void NoOfSpecificDaysThisMonth()
            int iDayCnt = 4; // Defaults to four days
            DayOfWeek dw = DayOfWeek.Wednesday;
            DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            int iRemainder = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) % 7;

            if ((dw >= firstDay.DayOfWeek) & ((dw - firstDay.DayOfWeek) < iRemainder))
                     iDayCnt = iDayCnt+1;
                    if ((dw < firstDay.DayOfWeek) & ((7+ dw - firstDay.DayOfWeek) < iRemainder))

                    iDayCnt = iDayCnt + 1;

The above gives the No Of Wednesdays for the Current month. If you want for any specific month / year you can tweak it a bit like:

DateTime firstDay = new DateTime(2012, DateTime.Now.Month, 1);
            int iRemainder = DateTime.DaysInMonth(2012, DateTime.Now.Month) % 7;

Other links that might be relevant:

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

1 comment:

  1. 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.