I am working on some custom rules in a time managment system and need to know how many hours in a shift have been before a certain time (19:00pm) and how many hours after. Shifts can start in the evening and finish in the morning so need to take that into account.
So far I have the below (this is just a snippet for one day) however it seems very clumsy and eloborate what I have written, can't help but feel I am missing a simpler solution, anyone have any ideas?
DateTime cutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 00);
string cutOffTimeOfDay = GetTimeOfDayFromDateTime(cutOffTime);
double baseMondayHours = 10.00;
baseMondayHours = (baseMondayHours - 0.5);
if (GetTimeOfDayOnlyFromDateTime(monday.ShiftStart.Value) == "AM" && GetTimeOfDayOnlyFromDateTime(monday.ShiftEnd.Value) == "PM"
&& monday.ShiftEnd.Value.TimeOfDay < cutOffTime.TimeOfDay)
{
postCutOffMondayHours = 0;
baseMondayHours = monday.HoursWorked.Value;
}
else
{
string endTimeOfDay = GetTimeOfDayFromDateTime(monday.ShiftEnd.Value);
double hoursAfterCutOff = GetDuration(cutOffTimeOfDay, endTimeOfDay);
postCutOffMondayHours = hoursAfterCutOff;
baseMondayHours = (baseMondayHours - hoursAfterCutOff);
}
public static string GetTimeOfDayFromDateTime(DateTime d)
{
return d.ToString("HH:mm") + " " + d.ToString("tt", CultureInfo.InvariantCulture);
}
public static string GetTimeOfDayOnlyFromDateTime(DateTime d)
{
return d.ToString("tt", CultureInfo.InvariantCulture).ToUpper();
}
public static double GetDuration(string startTime, string endTime)
{
DateTime start = DateTime.Parse(startTime);
DateTime end = DateTime.Parse(endTime);
if (start > end)
end = end.AddDays(1);
TimeSpan duration = end.Subtract(start);
return duration.TotalHours;
}
monday
was created with? \$\endgroup\$