获取一个月中特定星期的日期

时间:2018-12-13 06:45:21

标签: c# .net date datetime

我设法创建了一种方法,该方法返回特定月份和年份中的所有日期。

我的代码:

   public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
    {
        int days = DateTime.DaysInMonth(year, month);
        for (int day = 1; day <= days; day++)
        {
            yield return new DateTime(year, month, day);
        }
    }

现在我想要的是从一个月的特定星期数中获取所有日期

示例:我想获取December第二周中的日期,起始日期为Saturday

结果将是:

12/8/2018 Saturday
12/9/2018 Sunday
12/10/2018 Monday 
12/11/2018 Tuesday
12/12/2018 Wednesday
12/13/2018 Thursday
12/14/2018 Friday

1 个答案:

答案 0 :(得分:4)

唯一的困难是计算开始日期;让我们为此使用模算术

public static IEnumerable<DateTime> AllDatesInWeekOfMonth(int year, int month, int week) {
  DateTime start = new DateTime(year, month, 1);

  start = start
    .AddDays((CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - start.DayOfWeek + 7) % 7)
    .AddDays(week * 7 - 7);

  for (int i = 0; i < 7; ++i)
    if (start.Month == month) {
      yield return start;

      start = start.AddDays(1);
    }
}

演示:

// Different cultures have different first day of week
// In case of Invariant Culture week starts from Sunday
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

string test = string.Join(Environment.NewLine,
    AllDatesInWeekOfMonth(2018, 12, 2)
       .Select(date => date.ToString("dd MMMM yyyy (dddd)")));

Console.WriteLine(test);

结果:

09 December 2018 (Sunday)      // <- Week starts from Sunday
10 December 2018 (Monday)
11 December 2018 (Tuesday)
12 December 2018 (Wednesday)
13 December 2018 (Thursday)
14 December 2018 (Friday)
15 December 2018 (Saturday)