我的矛盾或者很简单的问题是从今天开始,以DD-MM-YY格式创建一个日期列表。假设我们今天有“11/04/2015”好吗?我有兴趣创建一个日期时间列表,该列表从2015年11月2日星期一到2015年11月8日星期日开始。这怎么可能?我最初想的是:
DateTime today = new DateTime.Now;
int posDayOfWeek = (int)today.DayOfWeek;
if (posDayOfWeek < 7 && posDayOfWeek > 1)
{
// And from there a black hole in my brain ....
}
我真的不知道怎么做....
谢谢 亲切 Cristian Capannini
答案 0 :(得分:7)
假设你总是想要周一到周日,你只需要:
DateTime today = DateTime.Today;
int currentDayOfWeek = (int) today.DayOfWeek;
DateTime sunday = today.AddDays(-currentDayOfWeek);
DateTime monday = sunday.AddDays(1);
// If we started on Sunday, we should actually have gone *back*
// 6 days instead of forward 1...
if (currentDayOfWeek == 0)
{
monday = monday.AddDays(-7);
}
var dates = Enumerable.Range(0, 7).Select(days => monday.AddDays(days)).ToList();
答案 1 :(得分:1)
请使用:
DayOfWeek[] days = {
DayOfWeek.Sunday,
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday };
很简单。很清楚。而且我已经为你输入了它。
答案 2 :(得分:0)
在网上搜索类似内容时,我找到了这个问题/答案主题并进行了扩展,以便根据从昨天开始的星期几创建排序顺序:
//create a sort order that starts yesterday
DateTime orderStartDate = DateTime.Today.AddDays(-1);
List<int> sortOrder = Enumerable.Range(0,7).Select(days => (int)orderStartDate.AddDays(days).DayOfWeek).ToList();
//sort collection using the index of the sortOrder
collection.AddRange(list.OrderBy(list => sortOrder.FindIndex(days => day == list.TargetDay)));