Click here to Skip to main content
15,915,764 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get dates from given weekdays in a given daterange

I have to give options for

1. selecting Date Range
eg:
01-01-2015 to 01-03-2015

2. Selecting weekday from combobox
example sunday,Monday etc

3. Selecting DayType like Ist ,second, third from checkboxlist

if i am selecting sunday and make tick on first and last in daytype then I want to get dates(in format dd/MM/yyyy) of first and last sunday within the date range.

how it possible

plz help me

Thanks in advance...
Posted
Comments
Sascha Lefèvre 3-Apr-15 1:24am    
What have you tried so far?
Sinisa Hajnal 3-Apr-15 2:27am    
http://www.codeproject.com/Articles/343366/DateTime-Extensions-to-Make-Some-Simple-Tasks-a-Li

I'm not sure i understand you well, but...

C#
DateTime startdate = new DateTime(2015,1,1);
DateTime enddate = new DateTime(2015,3,1);
	
List<datetime> days = new List<datetime>();

DayOfWeek choosenDay = DayOfWeek.Sunday;
int[] choosenOrder = new int[]{1,3,5};

while(startdate<enddate)>
{
	if(startdate.DayOfWeek==choosenDay)
	{
		days.Add(startdate);
		startdate=startdate.AddDays(6);
	}
        startdate=startdate.AddDays(1);
}
	
//get 1, 3 and 5 sunday
var qry = days.Select((d,i)=>new {day = d, index = (int)i+1}).Join(choosenOrder, item=>item.index, n=>n, (item, n)=>new{day = item.day, index=n});


Now, you can list all weekdays by using foreach loop:
C#
foreach(var d in qry)
{
    Console.WriteLine("{0} - {1}", d.index.ToString(), d.day.ToString("dd-MM-yyyy"));
}
 
Share this answer
 
v3
C#
   private static DateTime GetDate(
           DayOfWeek targetdayOfWeek,
           DateTime startDate,
           DateTime endDate,
           int numberOfOccurrences)
       {
           if (startDate > endDate)
           {
               throw new InvalidOperationException("The start date must not be greater than the end date");
           }
           int offset;
           if (targetdayOfWeek < startDate.DayOfWeek)
           {
               offset = 7 - (int)startDate.DayOfWeek + (int)targetdayOfWeek;
           }
           else
           {
               offset = targetdayOfWeek - startDate.DayOfWeek;
           }

  DateTime date = startDate.AddDays(offset + ((numberOfOccurrences - 1) * 7));
           if (date < startDate || date > endDate)
           {
               throw new InvalidOperationException("The number parameter is either too high or too low");
           }

return date;
       }
 
Share this answer
 

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