public static double[] GetWorkHours(DateTime start, DateTime end, TimeSpan workStartTime, TimeSpan workEndTime)
{
IList<double> result = new List<double>();
if (start > end)
{
throw new ArgumentException("Start date is later than end date");
}
DateTime currentDate = start.Date;
while (currentDate <= end.Date)
{
if (currentDate.DayOfWeek != DayOfWeek.Saturday && currentDate.DayOfWeek != DayOfWeek.Sunday)
{
TimeSpan realStartTime = GetStartTimeForDay(start, end, workStartTime, currentDate);
TimeSpan realEndTime = GetEndTimeForDay(start, end, workEndTime, currentDate);
if (realStartTime >= workEndTime || realEndTime <= workStartTime)
{
result.Add(0);
}
else
{
result.Add(GetHoursInTimePeriod(realStartTime, realEndTime));
}
}
currentDate = currentDate.AddDays(1);
}
return result.ToArray();
}
private static TimeSpan GetStartTimeForDay(DateTime start, DateTime end, TimeSpan workStartTime, DateTime day)
{
return day == start.Date ? (start.TimeOfDay < workStartTime ? workStartTime : start.TimeOfDay) : workStartTime;
}
private static TimeSpan GetEndTimeForDay(DateTime start, DateTime end, TimeSpan workEndTime, DateTime day)
{
return day == end.Date ? (end.TimeOfDay < workEndTime ? end.TimeOfDay : workEndTime) : workEndTime;
}
private static double GetHoursInTimePeriod(TimeSpan start, TimeSpan end)
{
return (end - start).TotalHours;
}
Source : https://stackoverflow.com/questions/47301975/c-sharp-get-working-hours-within-a-time-span
No comments:
Post a Comment