Windows Phone Developers

Showing posts with label C# DayOfWeek. Show all posts
Showing posts with label C# DayOfWeek. Show all posts

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;
                }
                else
                    if ((dw < firstDay.DayOfWeek) & ((7+ dw - firstDay.DayOfWeek) < iRemainder))
                {

                    iDayCnt = iDayCnt + 1;
                }
            
            MessageBox.Show(iDayCnt.ToString());
        }

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