获得下周的约会(C#)
我需要从表中获取数据,获得下周的约会(C#),c#,date,C#,Date,我需要从表中获取数据,Date是从下周(从周一到周日)到今天的日期 以下是我如何获取今天和明天日期的数据: public JsonResult GetTodayList() { var items = db.Appointments.Where(x => x.Date == DateTime.Today) .Select(x => new { title = x.Title,
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);
}
如何获取下周日期的数据?您可以尝试以下方法:
//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);
//下周一第一次获取(多亏了这个答案:https://stackoverflow.com/a/6346190/6170890 )
DateTime today=DateTime.today;
int daysUntilMonday=((int)DayOfWeek.Monday-(int)today.DayOfWeek+7)%7;
//如果今天是星期一,加上七天
如果(daysUntilMonday==0)
daysUntilMonday=7;
//为下周的开始和结束创建日期时间变量
DateTime nextWeekMonday=今天.AddDays(daysUntilMonday);
DateTime nextWeekSunday=nextWeekMonday.AddDays(6);
//最后,做你的选择
var items=db.appoints.Where(x=>x.Date>=nextWeekMonday&&x.datenew)
{
title=x.title,
时间=x.开始约会
}).ToList();
返回Json(items,JsonRequestBehavior.AllowGet);
我在计算即将上映的电影的放映时间时遇到了类似的问题
以下内容用于计算到下一个所需开始日期的偏移量
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;
}
然后,您可以根据计算的日期范围进行筛选。使用dupe计算下一个星期一和下一个星期一的可能重复,然后调整where子句
where(x=>x.date>=nextMonday和x.date
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