尝试比较两个时间之间的给定时间,看它是否在这些时间间隔内。例如如果给定时间是 00:00,我需要查明它是否在 21:00:00 到 7:00:00 之间。尝试了 TimeSpan.Compare 没有锁定,并且还使用 > 或 < 作为时间部分。
例如 给定间隔:
7:00:00 to 19:00:00 19:00:00 to 21:00:00 21:00:00 to 7:00:00
比较时间:
00:00:00 and 01:00:00
任何帮助将不胜感激。
更新问题:
看起来要求很模糊。要求基本上是传递时间 (TimeSpan) 并与两个 TimeSpan 间隔进行比较,看它们是否落入那些间隔。
例如假设员工在以下不同时间段工作,他们将获得不同的津贴:
Date Range: 2012-01-01 to 2012-31
19:00:00 to 21:00:00 ($10.00) 21:00:00 to 7:00:00 ($11.00) 7:00:00 to 19:00:00 ($12.00)
要计算员工的小时费率,我需要检查员工是否工作
- Between Date Range :2012-01-01 to 2012-31
- Between Time Range above.
并相应地应用 $ Rate。
最佳答案
您可以自己编写一个扩展方法,例如;
public static class TimeExtensions
{
public static bool IsBetween(this DateTime time, DateTime startTime, DateTime endTime)
{
if (time.TimeOfDay == startTime.TimeOfDay) return true;
if (time.TimeOfDay == endTime.TimeOfDay) return true;
if (startTime.TimeOfDay <= endTime.TimeOfDay)
return (time.TimeOfDay >= startTime.TimeOfDay && time.TimeOfDay <= endTime.TimeOfDay);
else
return !(time.TimeOfDay >= endTime.TimeOfDay && time.TimeOfDay <= startTime.TimeOfDay);
}
}
关于C# 比较两个时间间隔之间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631044/