如何从给定的开始日期和结束日期获取星期五日期, 例如:
我有课
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;
}
}
这就是我在主方法中调用它的方式:
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 方法,以便我的输出与范围之间的所有日期(星期五)一样?
答案 0 :(得分:3)
要回答您的问题,不要一次性打印 allFridays
,而是遍历列表的每个元素,即 allFridays
,转换为字符串然后打印
foreach(var friday in allFridays)
Console.WriteLine(friday);
为什么你得到 System.Collections.Generic.List[System.DateTime]
?
Console.WriteLine()
,对于非原始类型默认调用
.ToString()
函数打印 type
的它(如果它没有被覆盖)。在你的情况下,你
需要一个单独的日期而不是一种列表,所以你需要迭代
列表中的每个 DateTime
并打印每个日期。
一个班轮解决方案:
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));
答案 1 :(得分:3)
由于在您的使用部分,您已成功通过 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() 定义所需的日期模式。