C# 检查一个时间范围是否进入另一个时间范围
我有两个日期变量:C# 检查一个时间范围是否进入另一个时间范围,c#,C#,我有两个日期变量:startWork和endWork。 我需要定义人员是否包括23小时到05小时的工作时间。 例如: startWork.Hour|endWork.Hour|结果 21 5 Yes 22 3 Yes 12 21 No 23 8 Yes 21
startWork
和endWork
。
我需要定义人员是否包括23小时到05小时的工作时间。
例如:startWork.Hour
|endWork.Hour
|结果
21 5 Yes
22 3 Yes
12 21 No
23 8 Yes
21 8 Yes
7 9 No
我的代码:
if(startWork.Hour >= 23 && startWork.Hour <=5)
return true;
if(endWork.Hour >= 23 && endWork.Hour <=5)
return true;
如果(startWork.Hour>=23&&startWork.Hour=23&&endWork.Hour没有办法匹配X>=22和X,你应该像戴在评论中建议的那样使用日期时间
bool IsIn_23_To_5_Limits(DateTime startWork, DateTime endWork)
{
if (startWork >= endWork)
{
throw new ArgumentOutOfRangeException("You can't stop working before start working.");
}
// startWork after 23:00
// endWork before 05:00
// endWork is immediately on the next day after startWork
return startWork.Hour >= 23 && endWork.Hour < 5 && startWork.Day == endWork.Day - 1;
}
bool IsIn_23_至_5_限制(日期时间开始工作,日期时间结束工作)
{
如果(开始工作>=结束工作)
{
抛出新ArgumentOutOfRangeException(“在开始工作之前不能停止工作”);
}
//23:00后开始工作
//05:00前完工
//开工后第二天立即结束工作
返回startWork.Hour>=23&&endWork.Hour<5&&startWork.Day==endWork.Day-1;
}
最好使用实际的DateTime
对象作为开始和结束工作参数,因为它们实际上是时间点。除此之外,您始终可以向滚动值添加24,使其线性化,例如:
public bool CheckWorkHours(int start, int end, int checkStart, int checkEnd)
{
if (checkStart > checkEnd)
checkEnd += 24;
if (start > end)
end +=24;
//did he start working after (or on) checkEnd?
if (start >= checkEnd)
return false;
//did he end working before (or on) checkStart?
if (end <= checkStart)
return false;
// he did indeed work during the interval
return true;
}
public bool CheckWorkHours(int start、int end、int checkStart、int checkEnd)
{
如果(检查开始>检查结束)
checkEnd+=24;
如果(开始>结束)
末端+=24;
//他是在检查结束后开始工作的吗?
如果(开始>=检查结束)
返回false;
//他是在支票开始前结束工作的吗?
如果(结束检查开始));
但在使用日期数学时,我会尽量详细。我建议更改您的程序,这样您就可以存储实际的DateTime
值,而不仅仅是小时数。没错,我没有注意到这一点。我想我们希望工作时间严格在23-5小时内。
21-5: True
22-3: True
12-21: False
23-8: True
21-8: True
7-9: False
bool IsIn_23_To_5_Limits(DateTime startWork, DateTime endWork)
{
if (startWork >= endWork)
{
throw new ArgumentOutOfRangeException("You can't stop working before start working.");
}
// startWork after 23:00
// endWork before 05:00
// endWork is immediately on the next day after startWork
return startWork.Hour >= 23 && endWork.Hour < 5 && startWork.Day == endWork.Day - 1;
}
public bool CheckWorkHours(int start, int end, int checkStart, int checkEnd)
{
if (checkStart > checkEnd)
checkEnd += 24;
if (start > end)
end +=24;
//did he start working after (or on) checkEnd?
if (start >= checkEnd)
return false;
//did he end working before (or on) checkStart?
if (end <= checkStart)
return false;
// he did indeed work during the interval
return true;
}
return ((start < checkEnd) && (end > checkStart));