我有以下代码来计算startdate和enddate之间的分钟数。它还需要考虑工作时间(9到5),以便它不应在工作时间之外计算任何东西。
如果startdate和enddate在工作时间内有效,但是如果startdate超出工作时间(早上9点之前),则返回负数。
private static int GetMinutesBetweenTwoDates(DateTime startDate, DateTime endDate)
{
var minutes = from day in startDate.DaysInRangeUntil(endDate)
where !day.IsWeekendDay()
let start = Max(day.AddHours(9), startDate)
let end = Min(day.AddHours(17), endDate)
select (end - start).TotalMinutes;
}
private static DateTime Max(DateTime a, DateTime b)
{
return new DateTime(Math.Max(a.Ticks, b.Ticks));
}
private static DateTime Min(DateTime a, DateTime b)
{
return new DateTime(Math.Min(a.Ticks, b.Ticks));
}
public static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
.Select(dt => start.Date.AddDays(dt));
}
public static bool IsWeekendDay(this DateTime dt)
{
return dt.DayOfWeek == DayOfWeek.Saturday
|| dt.DayOfWeek == DayOfWeek.Sunday;
}
由于
答案 0 :(得分:1)
我认为您需要使用end <= start
来过滤案例,如果开始日期时间是在工作时间结束或结束日期时间早于工作时间开始之前,则可能会发生这种情况。更容易插入额外的where
子句:
private static int GetMinutesBetweenTwoDates(DateTime startDate, DateTime endDate)
{
var minutes = from day in startDate.DaysInRangeUntil(endDate)
where !day.IsWeekendDay()
let start = Max(day.AddHours(9), startDate)
let end = Min(day.AddHours(17), endDate)
where end > start
select (end - start).TotalMinutes;
return (int)minutes.Sum();
}
答案 1 :(得分:0)
以防万一,这个非常有用的时间段库: