Home > Blockchain >  How to select weekends with an interval between them?
How to select weekends with an interval between them?

Time:12-17

How can I select all weekends until the end of the year, with some criteria to be followed?

User input desired Weekend day:

18/12/2021

Software must out:

25/12/2022 (must be ignored)
01/01/2022
08/01/2022 (must be ignored)
15/01/2022
22/01/2022 (must be ignored)
29/01/2022 and so on...

What i have now:

public void GetWeekends() {
   var lastWorkedWeekend = dateTimePicker1.Value;
   var workedInSunday = checkBox1.Checked;
   var list = new List < DateTime > ();

   var weekends = GetDaysBetween(lastWorkedWeekend, DateTime.Today.AddDays(365)).Where(d => d.DayOfWeek == DayOfWeek.Saturday);
   var selected = true;
   for (int i = 0; i < weekends.Count(); i  ) {

     if (selected == false) {
       list.Add(weekends.ElementAt(i));
       selected = true;
     } else {
       selected = false;
     }
   }
 }

CodePudding user response:

I think I'd just scroll the input day forward until it was saturday (or calculate it, but i find the loop more self documenting than casting DayOfWeek to an int and factoring for sunday being 0) then add 14 days repeatedly. This skips over the 25th, etc..

var d = new DateTime(2021, 12, 18);

while(d.DayOfWeek != DayOfWeek.Saturday)
  d  = TimeSpan.FromDays(1);

while(d.Year == 2021){  //was your 2022 a typo? or maybe make this <= 2022.. I'm not sure what you want there..
  d  = TimeSpan.FromDays(14);
  Console.WriteLine(d);
}

You might prefer DateTime.AddDays()..

CodePudding user response:

Looks to me that you want to get the date of every second weekend from an initial date until the end of the year. In your example, you kinda bleed over to the next year.

public static void Main()
{   
    var dates = GetDateTimeRange(new DateTime(2021, 12, 18), new DateTime(2023, 1, 1), TimeSpan.FromDays(14));
    
    foreach (var dateTime in dates.Skip(1))
    {
        Console.WriteLine(dateTime);
    }
}

public static IEnumerable<DateTime> GetDateTimeRange(DateTime startingDate, DateTime endDate, TimeSpan interval)
{   
    var lastDate = startingDate;
    while (lastDate < endDate)
    {
        yield return lastDate;
        lastDate = lastDate.Add(interval);
    }
}

This returns

01/01/2022 00:00:00
01/15/2022 00:00:00
01/29/2022 00:00:00
02/12/2022 00:00:00
02/26/2022 00:00:00
03/12/2022 00:00:00
03/26/2022 00:00:00
04/09/2022 00:00:00
04/23/2022 00:00:00
05/07/2022 00:00:00
05/21/2022 00:00:00
06/04/2022 00:00:00
06/18/2022 00:00:00
07/02/2022 00:00:00
07/16/2022 00:00:00
07/30/2022 00:00:00
08/13/2022 00:00:00
08/27/2022 00:00:00
09/10/2022 00:00:00
09/24/2022 00:00:00
10/08/2022 00:00:00
10/22/2022 00:00:00
11/05/2022 00:00:00
11/19/2022 00:00:00
12/03/2022 00:00:00
12/17/2022 00:00:00
12/31/2022 00:00:00
  •  Tags:  
  • c#
  • Related