获取当前周的所有日期

时间:2017-03-30 15:55:50

标签: c# datetime c#-4.0

假设我将星期日 - 星期六视为一周,如何在c#中获取本周的所有日期?

例如,当前日期为30th March 2017,我需要的输出为

26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017

4 个答案:

答案 0 :(得分:7)

您可以尝试DateTimeFormat找出当前周的开始日期,然后 Linq 生成字符串:

  DateTime startOfWeek = DateTime.Today.AddDays(
      (int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - 
      (int) DateTime.Today.DayOfWeek);

  string result = string.Join("," + Environment.NewLine, Enumerable
    .Range(0, 7)
    .Select(i => startOfWeek
       .AddDays(i)
       .ToString("dd-MMMM-yyyy")));

如果是en-US文化,你会得到(周周日开始

26-March-2017,  // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017

如果是ru-RU文化,你会得到(周周一开始

27-марта-2017,  // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017

答案 1 :(得分:4)

假设星期日将是一周的开始日期,正如问题中提到的那样,我建议遵循解决方案。

var today = DateTime.Now.Date; // This can be any date.

Console.WriteLine(today.DayOfWeek);

var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)

Console.WriteLine(day);

const int totalDaysOfWeek = 7; // Number of days in a week stays constant.

for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
     Console.WriteLine(today.AddDays(i).Date);
}

答案 2 :(得分:0)

我找到了这个here

 DayOfWeek Day = DateTime.Now.DayOfWeek;
 int Days = Day - DayOfWeek.Monday; //here you can set your Week Start Day
 DateTime WeekStartDate = DateTime.Now.AddDays(-Days);
 DateTime WeekEndDate1 = WeekStartDate.AddDays(1);
 DateTime WeekEndDate2 = WeekStartDate.AddDays(2);
 DateTime WeekEndDate3 = WeekStartDate.AddDays(3);
 DateTime WeekEndDate4 = WeekStartDate.AddDays(4);
 DateTime WeekEndDate5 = WeekStartDate.AddDays(5);
 DateTime WeekEndDate6 = WeekStartDate.AddDays(6);

答案 3 :(得分:0)

我认为扩展方法是最有用的方法:

  public static IEnumerable<DateTime> GetDatesOfWeek(this DateTime date, CultureInfo ci) {
     Int32 firstDayOfWeek = (Int32) ci.DateTimeFormat.FirstDayOfWeek;
     Int32 dayOfWeek = (Int32) date.DayOfWeek;
     DateTime startOfWeek = date.AddDays(firstDayOfWeek - dayOfWeek);
     var valuesDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<Int32>();
     return valuesDaysOfWeek.Select(v => startOfWeek.AddDays(v));
  }

用法如下:

     DateTime myDate = DateTime.Today;
     IEnumerable<DateTime> result = myDate.GetDatesOfWeek(CultureInfo.CurrentCulture);
     foreach ( DateTime d in result ) {
        Console.WriteLine(d);
     }