[英]Check if the current time fall in range with different date in C#
i want to check the time that falls into two different date.我想检查属于两个不同日期的时间。 assume that i need to check from 10:30pm from this day up to 7am of tomorrow.假设我需要从今天晚上 10:30 到明天早上 7 点检查。
TimeSpan NightShiftStart = new TimeSpan(22, 30, 0);//10:30pm
TimeSpan NightShiftEnd = new TimeSpan(7, 0, 0); //7am
and compare it并比较它
if ((now > NightShiftStart ) && (now < NightShiftEnd )){}
timespan wont work on this i also tried时间跨度无法解决这个问题,我也尝试过
DateTime t1 = DateTime.Today.AddHours(22);
DateTime t2 = DateTime.Today.AddDays(1).AddHours(7);
still no luck.仍然没有运气。
You can use the TimeOfDay property and use that instead.您可以使用TimeOfDay 属性并改用它。 So your code should look like this所以你的代码应该是这样的
if (now.TimeOfDay > NightShiftStart || now.TimeOfDay < NightShiftEnd ){}
EDIT: While the above code is fine for what you asked, this way is a bit more generic and works for all kinds of shifts, as long as you know when they start and end:编辑:虽然上面的代码可以满足您的要求,但这种方式更通用,适用于各种班次,只要您知道它们何时开始和结束:
TimeSpan ShiftStart = new TimeSpan(22, 30, 0);//10:30pm
TimeSpan ShiftEnd = new TimeSpan(7, 0, 0); //7am
if ((ShiftStart > ShiftEnd && (now.TimeOfDay > ShiftStart || now.TimeOfDay < ShiftEnd))
|| (now.TimeOfDay > ShiftStart && now.TimeOfDay < ShiftEnd))
{
// ...
}
Usually you should use >= or <= for comparing either ShiftStart or ShiftEnd as you want an exact time to also fall into one of your shifts.通常您应该使用 >= 或 <= 来比较 ShiftStart 或 ShiftEnd,因为您希望确切的时间也属于您的一个班次。
Try this, It is a simple but effective way:试试这个,这是一个简单但有效的方法:
private bool CheckIfTimeIsBetweenShift(DateTime time)
{
var NightShiftStart = new TimeSpan(22, 30, 0);
var NightShiftEnd = new TimeSpan(7, 0, 0);
return NightShiftStart <= time.TimeOfDay && time.TimeOfDay >= NightShiftEnd;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.