c# - 获取一个月中特定一周的日期

标签 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);
        }
    }

现在我想要的是从某个月的特定周数获取所有日期

示例:我想获取 12 月第 2 周 开始的日期是 星期六.

结果是:

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

最佳答案

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

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)

关于c# - 获取一个月中特定一周的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53756354/

相关文章:

javascript - 使用 lodash 创建填充缺失值的新数组

date - 如何将毫秒转换为天、小时、分钟

c# - 使用没有身份的 [Authorize] 属性?

c# - Newtonsoft 忽略属性?

c# - 大型项目的 Entity Framework

c# - 显示按日期排序的数据

java - Solrj 将我的日期从 UTC 格式化为 CEST

c# - Linux后台进程

c# - HttpWebRequest 支持命名管道吗?

c# - 如何在 wpf 应用程序的配置文件中将自定义属性添加到 tracelistener