Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I have datetimepicker1(DTP1) in form. I want to know that, How many Sunday in selected month, and what is its date.

like.

January 2011

5 Sunday, date is 2/1/2011, 9/1/2011, 16/1/2011, 23/1/2011, 30/1/2011

I want date in text1,text2,text3,text4.
Posted
Updated 4-Jan-11 17:10pm
v2

1 solution

Below function will return you the list of dates.

CS:
C#
private List<DateTime> GetDates(DayOfWeek dayOfWeek, int month, int year)
{
   List<DateTime> dates = new List<DateTime>();
   int totalDaysCount = DateTime.DaysInMonth(year,month);
   int dayCount = 0;
   do
   {
       DateTime currentDate = new DateTime(year, month, ++dayCount);
       if (currentDate.DayOfWeek == dayOfWeek)
           dates.Add(currentDate);
   } while (totalDaysCount > dayCount);

   return dates;
}


VB:

VB
Public Function GetDates(ByVal dayOfWeek As DayOfWeek, ByVal month As Integer, ByVal year As Integer) As List(Of DateTime)
        Dim dates As New List(Of DateTime)
        Dim totalDaysCount As Integer = DateTime.DaysInMonth(year, month)
        Dim dayCount As Integer = 0
        Do While (totalDaysCount > dayCount)
            dayCount += 1
            Dim currentDate As New DateTime(year, month, dayCount)
            If (currentDate.DayOfWeek = dayOfWeek) Then
                dates.Add(currentDate)
            End If
        Loop

        Return dates
    End Function



Call wherever you wanted like below,

C#
List<DateTime> dates = GetDates(DayOfWeek.Sunday, 1, 2011);


C#
List<DateTime> dates = GetDates(DayOfWeek.Saturday, 4, 2011);


C#
List<DateTime> dates = GetDates(DayOfWeek.Friday, 11, 2009);


The "dates" will give all the Sundays in January, 2011.

Mark it as Answer if it helps you.
 
Share this answer
 
v4
Comments
jerrykid 4-Jan-11 22:04pm    
Perfect answer! I vote 5 - cheer
Venkatesh Mookkan 4-Jan-11 22:06pm    
Thank you @JerryKid
[no name] 4-Jan-11 23:02pm    
this is not working, i am using vb.net so plz.
Venkatesh Mookkan 4-Jan-11 23:11pm    
Answer updated with VB version.
TweakBird 4-Jan-11 23:12pm    
Use this URL to convert code C# to Vb.
http://www.developerfusion.com/tools/convert/csharp-to-vb/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900