在日期条款之间查找日期

本文关键字:日期 查找 之间 | 更新日期: 2023-09-27 18:36:52

我有一系列术语,其中有开始日期和结束日期。 我怎样才能找到今天是否介于条款之间。 代码是

  var termsforcurrentCalendar = UnitOfWork.SchoolTerms.Query().Where(x
  => x.SchoolCalendarId == currentCalendar.SchoolCalendarId).ToArray();
   var noOfTerms = termsforcurrentCalendar.Count();
    for (int i = 0; i < noOfTerms; i++)
   {
      if (DateTime.Today > termsforcurrentCalendar[i].EndDate)
      {
          if (i != noOfTerms)
       {
           if (DateTime.Today < termsforcurrentCalendar[i + 1].StartDate)
        {
           datetoBeChecked = termsforcurrentCalendar[i + 1].StartDate;
        }
     }
    }
   }

在日期条款之间查找日期

使用一点 linq 的优点怎么样:

var isTodayInTerm = termsforcurrentCalendar.Any(a => 
    DateTime.Today >= a.StartDate && DateTime.Today <= a.EndDate);

根据评论,要获得下一个术语:

var nextTerm = termsforcurrentCalendar.OrderBy(a => a.StartDate).FirstOrDefault(a =>
    a.StartDate >= DateTime.Today);
  var isTodayInTerm = termsforcurrentCalendar.Any(a =>DateTime.Today >= a.StartDate && DateTime.Today <= a.EndDate);
    if (!isTodayInTerm)
    {
        var firstAvailableDate = termsforcurrentCalendar.FirstOrDefault(z => z.StartDate > DateTime.Today);
        datetoBeChecked = firstAvailableDate.StartDate;
    }
var isTodayInTerm = termsforcurrentCalendar.Any(a =>DateTime.Today >= a.StartDate && DateTime.Today <= a.EndDate);
if (!isTodayInTerm)
{
    var firstAvailableDate = termsforcurrentCalendar.OrderBy(a=>a.StartDate).FirstOrDefault(z => z.StartDate > DateTime.Today);
    datetoBeChecked = firstAvailableDate.StartDate;
}