如何显示两个日期之间的所有星期五日期

How to display all Fridays Date between two dates

如何从给定的开始日期和结束日期获取星期五日期, 例如:

我有一个class

    public static class DateUtils
    {
       public static List<DateTime> GetWeekdayInRange(this DateTime from, DateTime to, DayOfWeek day)
       {
          const int daysInWeek = 7;
          var result = new List<DateTime>();
          var daysToAdd = ((int)day - (int)from.DayOfWeek + daysInWeek) % daysInWeek;

           do
           {
            from = from.AddDays(daysToAdd);
            result.Add(from);
            daysToAdd = daysInWeek;
           } 
           while (from < to);

        return result;
    }
}

这就是我在 main 方法中调用它的方式:

        var from = DateTime.Today; // 25/8/2019
        var to = DateTime.Today.AddDays(23); // 23/9/2019
        var allFriday = from.GetWeekdayInRange(to, DayOfWeek.Friday);

        Console.WriteLine(allFriday);



        Console.ReadKey();

我得到的错误:

System.Collections.Generic.List`1[System.DateTime]

我是新手,还在学习,如何调用 main 方法使我的输出与范围内的所有日期(星期五)一样?

为了回答您的问题,不要一次性打印 allFridays,而是遍历列表的每个元素,即 allFridays,转换为字符串,然后打印

foreach(var friday in allFridays)
    Console.WriteLine(friday);

为什么你得到 System.Collections.Generic.List[System.DateTime]

Console.WriteLine(), for non primitive type by default calls .ToString() function which prints type of it(if it is not overridden). In your case, you need an individual date not a type of List, so you need to iterate each DateTime from the list and print each date.


一个 Liner 解决方案:

Console.WriteLine(string.Join(Environment.NewLine, allFridays));

替代解决方案:

public static List<DateTime> GetWeekdayInRange(this DateTime @from, DateTime to, DayOfWeek day)
   {
      //Create list of DateTime to store range of dates
      var dates = new List<DateTime>();

      //Iterate over each DateTime and store it in dates list
      for (var dt = @from; dt <= to; dt = dt.AddDays(1))
         dates.Add(dt);

      //Filter date based on DayOfWeek
      var filteredDates = dates.Where(x => x.DayOfWeek == day).ToList();
      return filteredDates;
  }

  ...

var @from = DateTime.Today; // 25/8/2019
var to = DateTime.Today.AddDays(23); // 23/9/2019
var allFriday = @from.GetWeekdayInRange(to, DayOfWeek.Friday);

Console.WriteLine(string.Join(Environment.NewLine, allFridays));

.NET FIDDLE

因为在你的使用部分,你已经通过 GetWeekdayInRange 成功获得了结果。您可以使用这些方法打印日期:

方法一:

allFriday.ForEach(x => Console.WriteLine(x.ToShortDateString()));

方法二:

foreach (var friday in allFriday)
{
    Console.WriteLine(friday.ToShortDateString());
}

方法三:

for (var i = 0; i < allFriday.Count(); i++)
{
    Console.WriteLine(allFriday[i].ToShortDateString());
}

注意:ToShortDateString()是显示日期字符串的方法之一。您可以使用 ToString().

定义所需的日期模式