我正在研究时间管理系统中的一些自定义规则,需要知道一个班次在某一时间(晚上19:00)之前和之后有多少小时。轮班可以在晚上开始,在早上结束,所以需要考虑到这一点。
到目前为止,我有下面的内容(这只是一天的一个片段),但是它看起来非常笨拙,而且与我所写的内容相差甚远,我不禁觉得我缺少一个更简单的解决方案,有人有什么想法吗?
DateTime cutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 00);
string cutOffTimeOfDay = GetTimeOfDayFromDateTime(cutOffTime);
double baseMondayHours = 10.00;
baseMondayHours = (baseMondayHours - 0.5);
if (GetTimeOfDayOnlyFromDateTime(monday.ShiftStart.Value) == "AM" && GetTimeOfDayOnlyFromDateTime(monday.ShiftEnd.Value) == "PM"
&& monday.ShiftEnd.Value.TimeOfDay < cutOffTime.TimeOfDay)
{
postCutOffMondayHours = 0;
baseMondayHours = monday.HoursWorked.Value;
}
else
{
string endTimeOfDay = GetTimeOfDayFromDateTime(monday.ShiftEnd.Value);
double hoursAfterCutOff = GetDuration(cutOffTimeOfDay, endTimeOfDay);
postCutOffMondayHours = hoursAfterCutOff;
baseMondayHours = (baseMondayHours - hoursAfterCutOff);
}
public static string GetTimeOfDayFromDateTime(DateTime d)
{
return d.ToString("HH:mm") + " " + d.ToString("tt", CultureInfo.InvariantCulture);
}
public static string GetTimeOfDayOnlyFromDateTime(DateTime d)
{
return d.ToString("tt", CultureInfo.InvariantCulture).ToUpper();
}
public static double GetDuration(string startTime, string endTime)
{
DateTime start = DateTime.Parse(startTime);
DateTime end = DateTime.Parse(endTime);
if (start > end)
end = end.AddDays(1);
TimeSpan duration = end.Subtract(start);
return duration.TotalHours;
}
我不知道我是否遗漏了什么,但是内置的操作符--的 DateTime
正是你要找的东西?它返回的是 TimeSpan
两者之间 DateTime
,如果你能保证shiftStart < cutoffDateTime < shiftEnd,那么你只要用 TotalHours
的 TimeSpan
(但增加该检查只是一个额外的小的 if
)
var shiftStart = new DateTime(2020, 6, 2, 17, 0, 0);
var shiftEnd = new DateTime(2020, 6, 3, 6, 30, 0);
var cutoffDateTime = new DateTime(2020, 6, 2, 19, 0, 0);
var hoursWorkedBefore = (cutoffDateTime - shiftStart).TotalHours;
var hoursWorkedAfter = (shiftEnd - cutoffDateTime).TotalHours;