# Determine when a task will be completed

A friend of mine told me he had the following exercises at his interview :

You need to determine when a task will be completed if you are given :

1. A date when the task is started
2. The duration of the task in hours (how much hours it should take in total)
3. The starting time and end time of a working day

Weekends are not work days and you can assume that there are no holidays. Taking this in consideration what's the date when the task will be completed (hours and minutes are taken in consideration) ?

(The original exercise was meant to work with database but I simplified it a bit.)

Here's my solution to the problem :

public class Program
{
private static void Main()
{
DateTime startOfTask = new DateTime(2016, 2, 27, 10, 30, 0);

TimeSpan durationOftask = new TimeSpan(20, 30, 0);

TimeSpan startOfDay = new TimeSpan(8, 30, 0);
TimeSpan endOfDay = new TimeSpan(16, 0, 0);

}

TimeSpan endOfDay)
{
TimeSpan timeWorkingOnTask = new TimeSpan(0, 0, 0);
{
{
TimeSpan workTime = timeStartOfToday == startOfDay
? endOfDay - startOfDay
: endOfDay - timeStartOfToday;
{
}
else
{
break;
}
}
startOfDay.Minutes, 0);
}
}
}


I would add some checks to make sure the date is correct. For instance your start date is on a Saturday.

-- Updated from comment that task doesn't need to start during working times.

if (startTime.TotalDays > 1)
{
throw new ArgumentOutOfRangeException("startTime", "Start time greater than 24 hours");
}
if (endTime.TotalDays > 1)
{
throw new ArgumentOutOfRangeException("endTime", "End time greater than 24 hours");
}
if (endTime < startTime)
{
throw new ArgumentOutOfRangeException("endTime", "End time before start time");
}


For the logic you don't need to do a loop.

var numberOfDaystoStart = 0;
{
numberOfDaystoStart = 2;
}
{
numberOfDaystoStart = 1;
}
{
// Start time after the end of the work day need to move to the next day
numberOfDaystoStart = 1;
}

var startOffset = TimeSpan.Zero;
if (numberOfDaystoStart > 0 || startOfTask.TimeOfDay < startTime)
{
// IF started on weekend or after work hours adjust for first work day and start of working hours
startOffset =
startTime.Hours, startTime.Minutes, startTime.Seconds, startTime.Milliseconds) - startOfTask;
}

var workingtime = endTime.Subtract(startTime);
var nonWorkingTime = TimeSpan.FromDays(1) - workingtime;

// This will give long from C#

// add in the duration then add in the extra time for non work hours
// Add in the extra non-working time for each day
.AddDays((numbersOfDays/5)*2); // Add in 2 extra days for every 5 days of work

// Need to account for starting later in the week and rolling over weekend

var endOffset = TimeSpan.Zero;
{
endOffset = TimeSpan.FromDays(2);
}
// If we ended after the end of the day need to account for non-worktime