[Solved] Calculate last 16 Thusday’s from current date [closed]


This method works:

public static IList<DateTime> GetWeekDays(DateTime startDate, DayOfWeek day, int count, bool pastDays, bool includeStartDate)
{
    int start = (int)startDate.DayOfWeek;
    int desired = (int)day;
    int offset;
    int diff = Math.Abs(start - desired);
    if(!includeStartDate && start == desired)
        diff = 7;
    offset = pastDays ? (-1) * (7- diff) : diff;
    int weekDays = pastDays ? (-1) * 7 : 7;
    DateTime firstDay = startDate.AddDays(offset);
    IList<DateTime> dates = Enumerable.Range(0, count)
        .Select(i => firstDay.AddDays(i * weekDays))
        .ToList();
    return dates;
}

It supports both directions.

Usage is simple:

IList<DateTime> past16Wednesdays = GetWeekDays(DateTime.Today, DayOfWeek.Wednesday, 16, true, true);
foreach(DateTime dt in past16Wednesdays)
    Console.WriteLine(dt.ToString("d", CultureInfo.InvariantCulture));

Result is

11/20/2013
11/13/2013
11/06/2013
10/30/2013
10/23/2013
10/16/2013
10/09/2013
10/02/2013
09/25/2013
09/18/2013
09/11/2013
09/04/2013
08/28/2013
08/21/2013
08/14/2013
08/07/2013

0

solved Calculate last 16 Thusday’s from current date [closed]