计算两个日期之间经过的分钟数时出现问题



我有以下代码来计算开始日期和结束日期之间的分钟数。它还考虑了工作时间(9 到 5),因此它不应该计算工作时间以外的任何东西。

如果开始日期和结束日期在工作时间,

它可以正常工作,但如果开始日期在工作时间之外(上午 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;
}

谢谢

我认为您需要使用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();
}

以防万一,有一个非常有用的时间段库:

代码项目:.NET 的时间段库

相关内容

最新更新