mark_spencer
mark_spencer

Reputation: 393

Get next week dates (C#)

I need to get data from table where Date is from next week (from Monday to Sunday dates) from todays date.

Here is how I get data for today and tomorrow dates:

 public JsonResult GetTodayList()
    {
        var items = db.Appointments.Where(x => x.Date == DateTime.Today)
            .Select(x => new
            {
                title = x.Title,
                time = x.Start_appointment

            }).ToList();

        return Json(items, JsonRequestBehavior.AllowGet);

    }

    public JsonResult GetTommorowList()
    {
        DateTime tommorow = DateTime.Today.AddDays(1);
        var items = db.Appointments.Where(x => x.Date == tommorow)
            .Select(x => new
            {
                title = x.Title,
                time = x.Start_appointment
            }).ToList();
        return Json(items, JsonRequestBehavior.AllowGet);
    }

How I can get data for next week dates?

Upvotes: 4

Views: 2470

Answers (2)

Nkosi
Nkosi

Reputation: 247641

I had a similar issue when calculating the showtimes for upcoming movies.

The following was used to calculate the offset to the next desired start date.

public int CalculateOffset(DayOfWeek current, DayOfWeek desired) {
    // f( c, d ) = [7 - (c - d)] mod 7
    // f( c, d ) = [7 - c + d] mod 7
    // c is current day of week and 0 <= c < 7
    // d is desired day of the week and 0 <= d < 7
    int c = (int)current;
    int d = (int)desired;
    int offset = (7 - c + d) % 7;
    return offset == 0 ? 7 : offset;
}

with that

DateTime today = DateTime.Today;
var currentDayOfWeek = today.DayOfWeek;
var desiredDayOfWeek = DayOfWeek.Monday; //Start of the week

int offset = CalculateOffset(currentDayOfWeek, desiredDayOfWeek);

var minDate = today.AddDays(offset); // Monday 12:00:00 AM 
var maxDate = minDate.AddDays(7).AddSeconds(-1); // Sunday 12:59:59 PM

You can then filter based on the date range calculated.

Upvotes: 2

Nino
Nino

Reputation: 7115

you can try something like this:

//first get next monday (thanks to this answer: https://stackoverflow.com/a/6346190/6170890 )
DateTime today = DateTime.Today;
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
//if today is monday, add seven days
if (daysUntilMonday == 0)
    daysUntilMonday = 7;

//create DateTime variables for next week's beginning and end
DateTime nextWeekMonday = today.AddDays(daysUntilMonday);
DateTime nextWeekSunday = nextWeekMonday.AddDays(6);

//finally, do your select
var items = db.Appointments.Where(x => x.Date >= nextWeekMonday && x.Date <= nextWeekSunday)
.Select(x => new
{
    title = x.Title,
    time = x.Start_appointment
}).ToList();
return Json(items, JsonRequestBehavior.AllowGet);

Upvotes: 3

Related Questions