首先,我检查了这个解决方案:
Find if current time falls in a time range
并尝试比较那种解决方案的时间跨度
public Boolean CalculateDalUren(DateTime datum, TimeSpan? dalStart, TimeSpan? dalEnd)
{
Boolean isDal = false;
TimeSpan timeBetween = datum.TimeOfDay;
if ((timeBetween >= dalStart))&&(timeBetween < dalEnd)
{
isDal = true;
}
}
return isDal;
}
请注意,dalStart
是21:00或23:00,dalEnd
几乎总是07:00。我将DateTime
转换为Timespan
。
现在,如果Timespan例如是23:00,则时间大于或等于dalStart
,但因为(这是一个假设)它后来dalEnd
它仍会看到如果声明为假。反之,当它的02:00时。然后它不会迟于dalStart
但会早于dalEnd
。
我认为这是因为我的时间跨度为2天。从一天的21:00到第二天的07:00。这有解决方法吗?所以我可以检查第二天早上21:00到07:00之间的时间。
答案 0 :(得分:3)
我认为这符合您的要求。
如果dalEnd小于dalStart,它应该是第二天的TimeSpan。
public Boolean CalculateDalUren(DateTime datum, TimeSpan? dalStart, TimeSpan? dalEnd)
{
Boolean isDal = false;
DateTime StartDate = DateTime.Today;
DateTime EndDate = DateTime.Today;
//Check whether the dalEnd is lesser than dalStart
if (dalStart >= dalEnd)
{
//Increase the date if dalEnd is timespan of the Nextday
EndDate = EndDate.AddDays(1);
}
//Assign the dalStart and dalEnd to the Dates
StartDate = StartDate.Date + dalStart.Value;
EndDate = EndDate.Date + dalEnd.Value;
if ((datum >= StartDate) && (datum <= EndDate))
{
isDal = true;
}
return isDal;
}
试一试。
答案 1 :(得分:0)
创建两个日期,即实际日期的00:00,将dalStart,dalEnd timespan添加到它们和 if(datum&gt; datetimeFromDalStart和datum&lt; dateTimeFromDalEnd)....