C# - 在工作日开始的情况下,获得一个月内周列表的最佳方法是什么?

Dan*_*fer 18 c# datetime

我需要得到一个月的周列表,周一作为开始日.

例如,对于2009年2月,此方法将返回:

2/2/2009
2/9/2009
2/16/2009
2/23/2009
Run Code Online (Sandbox Code Playgroud)

小智 25

 // Get the weeks in a month

 DateTime date = DateTime.Today;
 // first generate all dates in the month of 'date'
 var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
 // then filter the only the start of weeks
 var weekends = from d in dates
                where d.DayOfWeek == DayOfWeek.Monday
                select d;
Run Code Online (Sandbox Code Playgroud)


Rob*_*ner 10

public static List<DateTime> GetWeeks(
    this DateTime month, DayOfWeek startOfWeek)
{
    var firstOfMonth = new DateTime(month.Year, month.Month, 1);
    var daysToAdd = ((Int32)startOfWeek - (Int32)month.DayOfWeek) % 7;
    var firstStartOfWeek = firstOfMonth.AddDays(daysToAdd);

    var current = firstStartOfWeek;
    var weeks = new List<DateTime>();
    while (current.Month == month.Month)
    {
        weeks.Add(current);
        current = current.AddDays(7);
    }

    return weeks;
}
Run Code Online (Sandbox Code Playgroud)