4

My paradoxical or perhaps trivial problem is to create me a list of the days in format DD - MM - YY from the date of today. Suppose we have today as " 11/04/2015 ". I want to create a list of datetime that starts exactly from Monday, 02.11.2015 to Sunday, 08.11.2015. How is this possible?

I thought initially :

DateTime today = new DateTime.Now;

int posDayOfWeek = (int)today.DayOfWeek;

if (posDayOfWeek < 7 && posDayOfWeek > 1)
{
    // And from there a black hole in my brain ....
}

How can I accomplish this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cristian Capannini
  • 69
  • 1
  • 2
  • 11

4 Answers4

15

Assuming you always want Monday to Sunday, you just need something like:

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();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Just use this:

DayOfWeek[] days = { 
    DayOfWeek.Sunday, 
    DayOfWeek.Monday, 
    DayOfWeek.Tuesday, 
    DayOfWeek.Wednesday, 
    DayOfWeek.Thursday, 
    DayOfWeek.Friday, 
    DayOfWeek.Saturday };

It's simple. It's clear. And I've already typed it out for you.

user2023861
  • 8,030
  • 9
  • 57
  • 86
0

Searching the web for something similar, I found this question/answer thread and expanded to create a sort order based on day of the week starting with yesterday:

//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)));
glennsl
  • 28,186
  • 12
  • 57
  • 75
LionDog823
  • 16
  • 2
0

Easy way:

Enumerable.Range(0, 7).Select(x => (DayOfWeek)x).ToList()
Simone S.
  • 1,756
  • 17
  • 18