C# - Duration between two DateTimes in minutes

后端 未结 9 1072
醉话见心
醉话见心 2020-12-16 11:58

I need to determine duration between two DateTimes in minutes.

However, there is a slight twist:

  • exclude weekends
  • only count minutes which a
9条回答
  •  星月不相逢
    2020-12-16 12:06

    static int WorkPeriodMinuteDifference(DateTime start, DateTime end)
    {
        //easier to only have to work in one direction.
        if(start > end)
            return WorkPeriodMinuteDifference(end, start);
        //if weekend, move to start of next Monday.
        while((int)start.DayOfWeek % 6 == 0)
            start = start.Add(new TimeSpan(1, 0, 0, 0)).Date;
        while((int)end.DayOfWeek % 6 == 0)
            end = end.Add(new TimeSpan(1, 0, 0, 0)).Date;
        //Move up to 07:00 or down to 19:00
        if(start.TimeOfDay.Hours < 7)
            start = new DateTime(start.Year, start.Month, start.Day, 7, 0, 0);
        else if(start.TimeOfDay.Hours > 19)
            start = new DateTime(start.Year, start.Month, start.Day, 19, 0, 0);
        if(end.TimeOfDay.Hours < 7)
            end = new DateTime(end.Year, end.Month, end.Day, 7, 0, 0);
        else if(end.TimeOfDay.Hours > 19)
            end = new DateTime(end.Year, end.Month, end.Day, 19, 0, 0);
    
        TimeSpan difference = end - start;
    
        int weeks = difference.Days / 7;
        int weekDays = difference.Days % 7;
        if(end.DayOfWeek < start.DayOfWeek)
            weekDays -= 2;
    
        return (weeks * 5 * 12 * 60) + (weekDays * 12 * 60) + difference.Hours * 60 + difference.Minutes
    }
    

提交回复
热议问题