获取下周的日期(C#)

时间:2017-08-27 13:39:07

标签: c# date

我需要从今天开始从下周(从星期一到星期日)Date的表中获取数据。

以下是我今天和明天的数据:

 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);
    }

如何获取下周日期的数据?

2 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情:

SNat

答案 1 :(得分:1)

在计算即将上映的电影的放映时间时,我遇到了类似的问题。

以下用于计算下一个所需开始日期的偏移量。

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;
}

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

然后,您可以根据计算的日期范围进行过滤。