Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get days of week by current week

Tags:

c#

After searching through stack overflow, I cant seem to find a solution. I've put together a chart (Chart.js) and I need to grab days of the current week bind that to the chart and match any days date to one stored in my db thus brining back all data based on that date.

So if anyone could give me any pointers on fetching List from the current week, that would be awesome.

I hope this is clear enough please feel free to ask more questions. Sorry no code struggling to get started. For me DateTime is an absolute nightmare to work with.

Regards,

like image 239
Tez Wingfield Avatar asked Nov 16 '14 16:11

Tez Wingfield


2 Answers

If you want to know the days of the current week, you need to:

Get the current day
Convert it to an integer
Subtract that many days from the current date. That gives you the date for Sunday.
Create a list, starting with Sunday.

So:

var now = DateTime.Now;
var currentDay = now.DayOfWeek;
int days = (int)currentDay;
DateTime sunday = now.AddDays(-days);
var daysThisWeek = Enumerable.Range(0, 7)
    .Select(d => sunday.AddDays(d))
    .ToList();
like image 38
Jim Mischel Avatar answered Sep 18 '22 10:09

Jim Mischel


You can use the DayOfWeek property of DateTime:

new DateTime(2014,11,16).DayOfWeek

So... to deal with a list of dates, first, let's make a list of dates:

var startDate = DateTime.Today;
var endDate = startDate.AddDays(7);
//the number of days in our range of dates
var numDays = (int)((endDate - startDate).TotalDays); 
List<DateTime> myDates = Enumerable
           //creates an IEnumerable of ints from 0 to numDays
           .Range(0, numDays) 
           //now for each of those numbers (0..numDays), 
           //select startDate plus x number of days
           .Select(x => startDate.AddDays(x))
           //and make a list
           .ToList();

and get the days of the week:

List<string> myDaysOfWeek = myDates.Select(d => d.DayOfWeek.ToString()).ToList();

if you want the week to start on (say) the previous Monday, you could alter startDate as follows:

startDate = startDate
           .AddDays(-(((startDate.DayOfWeek - DayOfWeek.Monday) + 7) % 7));

This works because we can treat the enumeration values of enum DayOfWeek as numbers, so we can subtract Monday(value 1) from Sunday(value 0), which gives -1... then we do a bit of a jiggle to wrap this value to 6 using modulo maths. If you subtract the resulting value (measured in days) from the start date, you end up on the previous Monday.

like image 182
spender Avatar answered Sep 18 '22 10:09

spender