我正在尝试制作一个自定义的 DateTime 对象集合,这些对象代表从当前日期时间到前进4周以及13周后的所有星期六。我试图通过最近关于集合顶部的当前日期时间来订购此集合。
TIA!
答案 0 :(得分:1)
请尝试以下代码。
它会从当前日期的-13
到+4
周内迭代您需要的几周,并将特定日期调整为您需要的日期(在这种情况下为Saturday
)
for (int i = -13; i <= 4; i++)
{
var dateBackWithIWeeks = DateTime.Now.AddDays(i * 7);
switch (dateBackWithIWeeks.DayOfWeek)
{
case DayOfWeek.Sunday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(-1);
break;
case DayOfWeek.Monday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(5);
break;
case DayOfWeek.Tuesday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(4);
break;
case DayOfWeek.Wednesday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(3);
break;
case DayOfWeek.Thursday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(2);
break;
case DayOfWeek.Friday:
dateBackWithIWeeks = dateBackWithIWeeks.AddDays(1);
break;
case DayOfWeek.Saturday:
break;
}
Console.WriteLine(dateBackWithIWeeks.Date);
}
答案 1 :(得分:1)
根据评论更新
注意:代码可能需要调整,具体取决于您定义“13周前”(以及“从现在开始的4周”)的方式 - 您是在考虑日历周,还是13 * 7天?以下代码可以追溯到13 * 7天。
这是一种方法:
以下是一个示例实现:
var saturdays = new List<DateTime>();
var daysInWeek = 7;
var startDate = DateTime.Today.Subtract(TimeSpan.FromDays(13 * daysInWeek));
// Adjust start date so it is the first Saturday after 13 weeks before today
startDate = startDate.AddDays(DayOfWeek.Saturday - startDate.DayOfWeek);
var endDate = DateTime.Today.Add(TimeSpan.FromDays(4 * daysInWeek));
for (var curDate = startDate; curDate <= endDate; curDate = curDate.AddDays(daysInWeek))
{
saturdays.Add(curDate);
}
// Order by date, descending
saturdays = saturdays.OrderByDescending(d => d).ToList();
// Output list of Saturdays to console for verification
saturdays.ForEach(s => Console.WriteLine(s.ToShortDateString()));
答案 2 :(得分:1)
这个怎么样:
public static void Main()
{
var start = DateTime.Now;
var saturdays = GetSaturdays(start, 13, 4).OrderBy(d => Math.Abs((start - d).Days));
foreach (var s in saturdays)
{
Console.WriteLine(s.ToLongDateString());
}
}
public static IEnumerable<DateTime> GetSaturdays(DateTime start, int weeksBack, int weeksForward)
{
var startingSat = start.AddDays(6 - (int)start.DayOfWeek);
for (int i = -weeksBack; i < weeksForward; i++)
{
yield return startingSat.AddDays(i * 7);
}
}
您的问题仍然不清楚您希望如何订购,但您可以更改排序以反映您想要的任何内容。听起来你希望它们按照它们与开始日期的接近程度来排序,这几乎肯定是没有意义的。如果您只是希望它们按日期降序排序(如果您实际想要的话,那就是您应该说的那样)然后只需将OrderBy
替换为:
.OrderByDescending(d => d);
这是fiddle
答案 3 :(得分:1)
List<DateTime> saturdays = new List<DateTime>();
for (int i = -13; i < 4; i++)
saturdays.Add(DateTime.Now.AddDays(i * 7 - (DateTime.Now.DayOfWeek - DayOfWeek.Saturday)));
DateTime today = DateTime.Now;
var more_recent = saturdays.OrderBy(day => Math.Abs(today.Subtract(day).Days)).ToList();